Returning a 404 from an explicitly typed ASP.NET Core API controller (not IActionResult)

前端 未结 4 1806
春和景丽
春和景丽 2020-12-24 00:01

ASP.NET Core API controllers typically return explicit types (and do so by default if you create a new project), something like:

[Route(\"api/[controller]\")         


        
4条回答
  •  时光说笑
    2020-12-24 00:43

    What you're doing with returning "Explicit Types" from the controller is isn't going to cooperate with your requirement to explicitly deal with your own response code. The simplest solution is to go with IActionResult (like others have suggested); However, you can also explicitly control your return type using the [Produces] filter.

    Using IActionResult.

    The way to get control over the status results, is you need to return a IActionResult which is where you can then take advantage of the StatusCodeResult type. However, now you've got your issue of wanting to force a partiular format...

    The stuff below is taken from the Microsoft Document: Formatting Response Data -Forcing a Particular Format

    Forcing a Particular Format

    If you would like to restrict the response formats for a specific action you can, you can apply the [Produces] filter. The [Produces] filter specifies the response formats for a specific action (or controller). Like most Filters, this can be applied at the action, controller, or global scope.

    Putting it all together

    Here's an example of control over the StatusCodeResult in addition to control over the "explicit return type".

    // GET: api/authors/search?namelike=foo
    [Produces("application/json")]
    [HttpGet("Search")]
    public IActionResult Search(string namelike)
    {
        var result = _authorRepository.GetByNameSubstring(namelike);
        if (!result.Any())
        {
            return NotFound(namelike);
        }
        return Ok(result);
    }
    

    I'm not a big supporter of this design pattern, but I have put those concerns in some additional answers to other people's questions. You will need to note that the [Produces] filter will require you to map it to the appropriate Formatter / Serializer / Explicit Type. You could take a look at this answer for more ideas or this one for implementing a more granular control over your ASP.NET Core Web API.

提交回复
热议问题