首页 文章

如何从Controller返回特定的状态代码而没有内容?

提问于
浏览
74

我希望下面的示例控制器返回没有内容的状态代码418 . 设置状态代码很容易,但似乎需要做一些事情来发出请求结束的信号 . 在ASP.NET Core之前的MVC或WebForms中,可能是对_1245350的调用,但它在ASP.NET核心中如何工作 Response.End 不存在?

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();   
    }
}

2 回答

  • 0

    this.HttpContext.Response.StatusCode = 418; //我是茶壶如何结束请求?

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

    return StatusCode(418);
    

    您可以使用 StatusCode(???) 返回任何HTTP状态代码 .

    此外,您可以使用专用结果:

    成功:

    • return Ok() ←Http状态码200

    • return Created() ←Http状态码201

    • return NoContent(); ←Http状态码204

    客户端错误:

    • return BadRequest(); ←Http状态码400

    • return Unauthorized(); ←Http状态码401

    • return NotFound(); ←Http状态码404

    更多细节:

  • 173

    此代码可能适用于非.NET Core MVC控制器:

    this.HttpContext.Response.StatusCode = 418; // I'm a teapot
    return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);
    

相关问题