Null response returns a 204

♀尐吖头ヾ 提交于 2021-01-26 23:53:17

问题


My controller returns a 204 when I do a GET request and I don't find any data.

[Route("user/v1/[controller]")]
public class UserLoginController : Controller
{
    [HttpGet]
    public async Task<UserLogin> Get(int userId)
    {
        var userLoginLogic = new UserLoginLogic();

        return await userLoginLogic.GetUserLogin(userId);
    }
}

This is only for GET requests, POST, PUT, DELETE return a 200 empty response. This messes with my swagger definition which has a response defined for a 200 response, and I would rather be consistent.

The 204 would be fine if I was serving HTML out of this controller but it is for a REST API.

How do I get it to return a 200?


回答1:


With the new ActionResult<T> in v2.1+ you can also refactor to specifically tell the controller to return Ok 200 using the Ok() helper methods

[Route("user/v1/[controller]")]
public class UserLoginController : Controller {
    [HttpGet]
    public async Task<ActionResult<UserLogin>> Get(int userId) {
        var userLoginLogic = new UserLoginLogic();
        var model = await userLoginLogic.GetUserLogin(userId);
        return Ok(model);
    }
}

however this can be misleading if there is in fact no content to return. Consider using an appropriate response status

[Route("user/v1/[controller]")]
public class UserLoginController : Controller {
    [HttpGet]
    public async Task<ActionResult<UserLogin>> Get(int userId) {
        var userLoginLogic = new UserLoginLogic();
        var model = await userLoginLogic.GetUserLogin(userId);
        if(model == null) return NotFound(); //404
        return Ok(model); //200
    }
}

If intent on returning 200 Ok with no content use ControllerBase.Ok() method

Creates a OkResult object that produces an empty Status200OK response.

[Route("user/v1/[controller]")]
public class UserLoginController : Controller {
    [HttpGet]
    public async Task<ActionResult<UserLogin>> Get(int userId) {
        var userLoginLogic = new UserLoginLogic();
        var model = await userLoginLogic.GetUserLogin(userId);
        if(model == null) return Ok(); //200 with no content
        return Ok(model); //200
    }
}

Reference Controller action return types in ASP.NET Core Web API:




回答2:


See:

  • https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-3.1#special-case-formatters
  • https://www.colabug.com/2020/0224/7036191/
  • https://weblog.west-wind.com/posts/2020/Feb/24/Null-API-Responses-and-HTTP-204-Results-in-ASPNET-Core

services.AddControllers(opt =>  // or AddMvc()
{
    // remove formatter that turns nulls into 204 - No Content responses
    // this formatter breaks Angular's Http response JSON parsing
    opt.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
})


来源:https://stackoverflow.com/questions/51411693/null-response-returns-a-204

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!