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

前端 未结 4 1837
春和景丽
春和景丽 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:42

    In order to accomplish something like that(still, I think that the best approach should be using IActionResult), you can follow, where you can throw an HttpResponseException if your Thing is null:

    // GET api/things/5
    [HttpGet("{id}")]
    public async Task GetAsync(int id)
    {
        Thing thingFromDB = await GetThingFromDBAsync();
        if(thingFromDB == null){
            throw new HttpResponseException(HttpStatusCode.NotFound); // This returns HTTP 404
        }
        // Process thingFromDB, blah blah blah
        return thing;
    }
    

提交回复
热议问题