如何从控制器返回特定的状态码并且没有内容?

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;//我是茶壶

如何结束请求?

尝试其他解决方案,只需:

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 200
  • return Created() ← Http status code 201
  • return NoContent(); ← Http status code 204

客户端错误:

  • return BadRequest(); ← Http状态码400
  • return Unauthorized(); ← Http状态码401
  • return NotFound(); ← Http状态码404
  • return BadRequest(); ← Http status code 400
  • return Unauthorized(); ← Http status code 401
  • return 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

这篇关于如何从控制器返回特定的状态码并且没有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)