c# – 空响应返回204
作者:互联网
当我执行GET请求时,我的控制器返回204并且我找不到任何数据.
[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);
}
}
这仅适用于GET请求,POST,PUT,DELETE返回200空响应.这与我的招摇定义相混淆,该定义具有针对200响应定义的响应,并且我宁愿保持一致.
如果我从这个控制器提供HTML,那么204就可以了,但它适用于REST API.
如何让它返回200?
解决方法:
使用新的ActionResult< T>在v2.1中你也可以重构你可以专门告诉控制器使用Ok()辅助方法返回Ok 200
[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);
}
}
但是,如果实际上没有内容可以返回,这可能会产生误导.考虑使用适当的响应状态
[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
}
}
如果意图返回200 Ok没有内容
[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
}
}
参考Controller action return types in ASP.NET Core Web API:
标签:c,asp-net-core,asp-net-core-2-1 来源: https://codeday.me/bug/20190622/1262150.html