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


119

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

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

Answers:


246

this.HttpContext.Response.StatusCode = 418; // I'm a teapot

如何结束请求?

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

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


更多细节:


62
there is no dedicated result for 418 Microsoft,这里严重缺少功能。
杰西

1
我已经更新了我的答案,因为我发现NoContent();它返回HTTP错误代码204
卢卡斯Makowej

1
这是ControllerBase类的链接,在这里定义了所有这些现成的结果类型。docs.microsoft.com/en-us/aspnet/core/api/…–
Technetium

3
不过,您仍然可以StatusCodesMicrosoft.AspNetCore.Http命名空间(github.com/aspnet/HttpAbstractions/blob/dev/src/…)中使用。
Lukasz Makowej

1
是的,它将起作用,或者您可以使用StatusCode(StatusCodes.Status412PreconditionFailed);
Lukasz Makowej

4

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

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

4

如果有人想IHttpActionResult在Web API项目中使用a进行此操作,则下面的内容可能会有所帮助。

// GET: api/Default/
public IHttpActionResult Get()
{
    //return Ok();//200
    //return StatusCode(HttpStatusCode.Accepted);//202
    //return BadRequest();//400
    //return InternalServerError();//500
    //return Unauthorized();//401
    return Ok();
}

1

查看如何创建当前的对象结果。这是BadRequestObjectResult。只是ObjectResult的扩展,带有值和StatusCode。

https://github.com/aspnet/Mvc/blob/master/src/Microsoft.AspNetCore.Mvc.Core/BadRequestObjectResult.cs

我以与408相同的方式创建了TimeoutExceptionObjectResult。

/// <summary>
/// An <see cref="ObjectResult"/> that when executed will produce a Request Timeout (408) response.
/// </summary>
[DefaultStatusCode(DefaultStatusCode)]
public class TimeoutExceptionObjectResult : ObjectResult
{
    private const int DefaultStatusCode = StatusCodes.Status408RequestTimeout;

    /// <summary>
    /// Creates a new <see cref="TimeoutExceptionObjectResult"/> instance.
    /// </summary>
    /// <param name="error">Contains the errors to be returned to the client.</param>
    public TimeoutExceptionObjectResult(object error)
        : base(error)
    {
        StatusCode = DefaultStatusCode;
    }
}

客户:

if (ex is TimeoutException)
{
    return new TimeoutExceptionObjectResult("The request timed out.");
}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.