2
如何爲NotFoundObjectResult結果創建自定義頁面?asp.net核心中NotFoundObjectResult的自定義頁面
實際上,當我返回這個結果時,應用程序只在頁面中顯示id。
return new NotFoundObjectResult(id);
我每次得到NotFoundObjectResult時都需要重定向到「/ errors/notfound」。
如何爲NotFoundObjectResult結果創建自定義頁面?asp.net核心中NotFoundObjectResult的自定義頁面
實際上,當我返回這個結果時,應用程序只在頁面中顯示id。
return new NotFoundObjectResult(id);
我每次得到NotFoundObjectResult時都需要重定向到「/ errors/notfound」。
您可以將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);