问题描述
我希望下面的示例控制器返回没有内容的状态代码 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;//我是茶壶
如何结束请求?
尝试其他解决方案,只需:
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状态码200return Created()
← Http状态码201return NoContent();
← Http状态码204
return Ok()
← Http status code 200return Created()
← Http status code 201return NoContent();
← Http status code 204
客户端错误:
return BadRequest();
← Http状态码400return Unauthorized();
← Http状态码401return 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
这篇关于如何从控制器返回特定的状态码并且没有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!