Sie können app.UseStatusCodePagesWithReExecute
oder app.UseStatusCodePagesWithRedirect
zu der Pipeline hinzufügen (vor app.UseMvc
). Dies wird jede Antwort mit Statuscode zwischen 400 und 600 abfangen, die hat noch keine Körper.
In Ihrem Startup-Klasse:
app.UseStatusCodePagesWithReExecute("/statuscode/{0}");
dann einen neuen Controller hinzufügen:
public class HttpStatusController: Controller
{
[HttpGet("statuscode/{code}")]
public IActionResult Index(HttpStatusCode code)
{
return View(code);
}
}
und Blick Aufrufe/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>
Sie jetzt muss nur den gewünschten Statuscode von einem Controller zurückgeben, ohne einen optionalen Körper hinzuzufügen:
//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);