asp.net-mvcasp.net-core-mvcpostmanasp.net-mvc-controller

Cannot get a response from a Web API call


I have the following in the TreeController controller in a small web API:

    [HttpGet("GetDirectories")]
    public IActionResult GetDirectories()
    {
        var baseDir = _config["QuickShare:BaseDir"];
        if (string.IsNullOrWhiteSpace(baseDir))
        {
            throw new InvalidOperationException("'QuickShare:BaseDir' is not configured");
        }
        var ret = GetDirectories(baseDir); ;
        return Json(ret);
    }
    private List<DirectoryInfo> GetDirectories(string parentDir)
    {
        var dirInfo = new DirectoryInfo(parentDir);
        return dirInfo.GetDirectories("*", SearchOption.TopDirectoryOnly).ToList();
    }

When I try and call this action from Postman, I get told

Could not get any response There was an error connecting to http://localhost:59243/api/Tree/GetDirectories.

Now the default, test, controller that comes with the project template is unchanged:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] {"value1", "value2"};
    }
    ...
}

And when I have the API running in Visual Studio, I can get a proper response from the Values controller, but not from the TreeController, yet they are almost exactly the same. And, when I call the Tree/GetDirectories` action, a breakpoint in that action method is hit, and I can single step through the very few lines that my method has, and they all execute fine.

The problem only becomes apparent when that last line of the action executes:

return Json(ret);

Then I get shown that Postman Could not get any response despite no exception being raised; while debugging the code, it looks like everything should work fine, and the requests to the Values controller work fine.


Solution

  • Your action method should return either the specific result type (JsonResult when you return Json ) or IActionResult.

    Example:

     [HttpGet("GetDirectories")]
        public JsonResult GetDirectories()
        {
            var baseDir = _config["QuickShare:BaseDir"];
            if (string.IsNullOrWhiteSpace(baseDir))
            {
                throw new InvalidOperationException("'QuickShare:BaseDir' is not configured");
            }
            var ret = GetDirectories(baseDir);
            return Json(ret);
        }
    

    OR

    [HttpGet("GetDirectories")]
    public IActionResult GetDirectories()
    {
        var baseDir = _config["QuickShare:BaseDir"];
        if (string.IsNullOrWhiteSpace(baseDir))
        {
            throw new InvalidOperationException("'QuickShare:BaseDir' is not configured");
        }
        var ret = GetDirectories(baseDir) ;
        return Ok(ret);
    }
    

    You can get more help from Microsoft Documentation: Formatting Response Data