如何从控制器返回特定的状态代码而没有内容? [英] How to return a specific status code and no contents from Controller?
问题描述
我希望下面的示例控制器返回不包含任何内容的状态代码418.设置状态代码很容易,但是似乎需要完成一些操作以发出请求结束的信号.在ASP.NET Core之前的MVC或WebForms中,这可能是对Response.End()
的调用,但是在Response.End
不存在的ASP.NET Core中它如何工作?
I want the example controller below to return a status code 418 with no contents. Setting the status code is easy enough but then it seems like there is something that needs to be done to signal the end of the request. In MVC prior to ASP.NET Core or in WebForms that might be a call to Response.End()
but how does it work in ASP.NET Core where Response.End
does not exist?
public class ExampleController : Controller
{
[HttpGet][Route("/example/main")]
public IActionResult Main()
{
this.HttpContext.Response.StatusCode = 418; // I'm a teapot
// How to end the request?
// I don't actually want to return a view but perhaps the next
// line is required anyway?
return View();
}
}
推荐答案
this.HttpContext.Response.StatusCode = 418; // I'm a teapot
如何结束请求?
尝试其他解决方案,就是:
Try other solution, just:
return StatusCode(418);
您可以使用StatusCode(???)
返回任何HTTP状态代码.
You could use StatusCode(???)
to return any HTTP status code.
另外,您可以使用专用结果:
Also, you can use dedicated results:
成功:
-
return Ok()
←Http状态码200 -
return Created()
←Http状态码201 -
return NoContent();
←Http状态码204
return Ok()
← Http status code 200return Created()
← Http status code 201return NoContent();
← Http status code 204
客户端错误:
-
return BadRequest();
←Http状态码400 -
return Unauthorized();
←Http状态码401 -
return NotFound();
←Http状态码404
return BadRequest();
← Http status code 400return Unauthorized();
← Http status code 401return NotFound();
← Http status code 404
更多详细信息:
- ControllerBase类(感谢@Technetium )
- StatusCodes.cs (在ASP.NET Core中可用的常量)
- Wiki上的HTTP状态代码
- HTTP状态代码IANA
- ControllerBase Class (Thanks @Technetium)
- StatusCodes.cs (consts aviable in ASP.NET Core)
- HTTP Status Codes on Wiki
- HTTP Status Codes IANA
这篇关于如何从控制器返回特定的状态代码而没有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!