c# - 为 ASP.NET Core MVC 显示 404 Not Found 页面

标签 c# asp.net iis asp.net-core asp.net-core-mvc

我正在使用下面的中间件为 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/

相关文章:

asp.net - Fck 编辑器 - 更新面板

c# - 如何将 C# 变量添加到 html 模态

IIS applicationHost 'setEnvironment' 属性

c# - ngen 是如何工作的?

asp.net - 在 Web 应用程序中存储文件上传的位置

c# - AuthenticationContext 不包含 AcquireToken 定义?

asp.net - 加快您的 IIS

asp.net - 如何在 Visual Studio 2012 中重命名 IIS Express 网站

c# - 创建两个具有相同友好名称的应用程序域

c# - 如何使用可执行文件打开文本文件?