如何为 NotFoundObjectResult 结果创建自定义页面?
实际上,当我返回此结果时,应用程序仅在页面中显示 id。
return new NotFoundObjectResult(id);
每次获得 NotFoundObjectResult 时,我都需要重定向到“/errors/notfound”。
最佳答案
您可以将 app.UseStatusCodePagesWithReExecute
或 app.UseStatusCodePagesWithRedirect
添加到管道(在 app.UseMvc
之前)。这将拦截任何状态代码在 400 到 600 之间且尚无正文的响应。
在您的 Startup 类中:
app.UseStatusCodePagesWithReExecute("/statuscode/{0}");
然后添加一个新的 Controller :
public class HttpStatusController: Controller
{
[HttpGet("statuscode/{code}")]
public IActionResult Index(HttpStatusCode code)
{
return View(code);
}
}
并添加一个 View Views/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>
现在您只需从 Controller 返回所需的状态代码,无需添加任何可选主体:
//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);
关于asp.net-core - asp.net core 中 NotFoundObjectResult 的自定义页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39674609/