app.UseStatusCodePagesWithReExecute
またはapp.UseStatusCodePagesWithRedirect
をパイプラインに追加することができます(app.UseMvc
より前)。これにより、にボディがまだありませんが、のステータスコード400〜600の応答が代行受信されます。スタートアップクラスで
:
app.UseStatusCodePagesWithReExecute("/statuscode/{0}");
次に、新しいコントローラを追加:
public class HttpStatusController: Controller
{
[HttpGet("statuscode/{code}")]
public IActionResult Index(HttpStatusCode code)
{
return View(code);
}
}
を、ビュービュー/はhttpStatus/Index.cshtmlを追加します。
@model System.Net.HttpStatusCode
@{
ViewData["Title"] = "Error " + (int)Model;
}
<div class="jumbotron">
<h1>Error @((int)Model)!</h1>
<p><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></p>
</div>
今、あなたは、任意のボディを追加することなく、コントローラから目的のステータスコードを返すだけでよい:
//These would end up in the new HttpStatus controller, they just specify the status code
return StatusCode(404);
return new StatusCodeResult(404);
//Any of these won't, as they add either the id or an object to the response's body
return StatusCode(404, 123);
return StatusCode(404, new { id = 123 });
return new NotFoundObjectResult(123);