ASP.NET Core equivalent of ASP.NET MVC 5's HttpException

后端 未结 6 1850
攒了一身酷
攒了一身酷 2020-12-02 11:59

In ASP.NET MVC 5 you could throw a HttpException with a HTTP code and this would set the response like so:

throw new HttpException((int)HttpStatusCode.BadReq         


        
6条回答
  •  余生分开走
    2020-12-02 12:32

    Starting from ASP.NET Core 3 you can use ActionResult to return HTTP status code:

    [HttpGet("{id}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public ActionResult GetByItemId(int id)
    {
    ...
        if (result == null)
        {
            return NotFound();
        }
    
        return Ok(result);
    }
    

    More details are here: https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-3.1

提交回复
热议问题