我正在使用下面的中间件为 HTTP 状态代码 400 到 599 设置错误页面。因此访问 /error/400
显示 400 Bad Request 错误页面。
application.UseStatusCodePagesWithReExecute("/error/{0}");
[Route("[controller]")]
public class ErrorController : Controller
{
[HttpGet("{statusCode}")]
public IActionResult Error(int statusCode)
{
this.Response.StatusCode = statusCode;
return this.View(statusCode);
}
}
但是,访问 /this-page-does-not-exist
会导致通用 IIS 404 Not Found 错误页面。
有没有办法处理不匹配任何路由的请求?在 IIS 接管之前,我如何处理这种类型的请求?理想情况下,我想将请求转发到 /error/404
,以便我的错误 Controller 可以处理它。
在 ASP.NET 4.6 MVC 5 中,我们必须使用 Web.config 文件中的 httpErrors 部分来执行此操作。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<error statusCode="404" responseMode="ExecuteURL" path="/error/404/" />
</httpErrors>
</system.webServer>
</configuration>
最佳答案
我找到的最好的教程之一是:https://joonasw.net/view/custom-error-pages
总结在这里:
1.
首先添加一个 Controller ,如 ErrorController
,然后向其添加此操作:
[Route("404")]
public IActionResult PageNotFound()
{
string originalPath = "unknown";
if (HttpContext.Items.ContainsKey("originalPath"))
{
originalPath = HttpContext.Items["originalPath"] as string;
}
return View();
}
注意:您可以将操作添加到另一个现有 Controller ,如 HomeController
。
2。
现在添加 PageNotFound.cshtml
View 。像这样:
@{
ViewBag.Title = "404";
}
<h1>404 - Page not found</h1>
<p>Oops, better check that URL.</p>
3。
重要的部分就在这里。将此代码添加到 Startup
类中的 Configure
方法中:
app.Use(async (ctx, next) =>
{
await next();
if(ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
{
//Re-execute the request so the user gets the error page
string originalPath = ctx.Request.Path.Value;
ctx.Items["originalPath"] = originalPath;
ctx.Request.Path = "/error/404";
await next();
}
});
请注意,它必须在路由配置之前添加,例如 app.UseEndpoints...
。
关于c# - 为 ASP.NET Core MVC 显示 404 Not Found 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31606521/