未处理的异常未被路由到我的自定义错误页面

Unhandled expections in are not being routed to my custom error page

我的理解是,如果你添加了 app.UseExceptionHandler(); 并给它一个路径,那么 ASP.Net 应该在出现代码中没有捕获到的错误时加载该页面,但在我的情况下我仍然看到正常的 "Http 500 Internal Server Error" 页面。我可以采用我提供的路径 UseExceptionHandler() 并将其正确放置在我的浏览器中,它可以很好地加载页面,因此我知道路径和页面工作。我是否想念它是如何工作的,它坏了,还是我做错了什么?

Startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //if (env.IsDevelopment())
    //{
    //    app.UseDeveloperExceptionPage();
    //}

    app.UseExceptionHandler("/Error/ServerError");
    app.UseIISPlatformHandler();
    app.UseSession();
    app.UseStaticFiles();
    app.UseStatusCodePagesWithReExecute("/Error/PageNotFound");
    app.UseMvc();
}

错误页面代码:

//Get: "/Error/ServerError"
[Route("Error/ServerError")]
public IActionResult ServerError()
{
    return View(); //View is inside the Shared folder.
}

页面查看错误:

<p>
    @ViewData["ErrorMessage"]
</p>

请注意 "Page not Found" 错误被路由到 /Error/PageNotFound 没有问题,只是其他错误不是。

编辑: 作为测试,我将字符串从 UseStatusCodePagesWithReExecute 复制到 UseExceptionHandler,但仍然得到通用的 500 错误页面。

编辑 2: 我应该注意,我正在以两种方式测试这个错误。第一种是简单地执行操作 throw new DivideByZeroException();,另一种是让 LINQ to Entities 调用已脱机的数据库(并因此抛出 SqlException)。这两种方式都只是 return 默认值 HTTP 500 Internal Server Error 而不是我的自定义错误。

我原本认为 UseXXX 函数的顺序很重要,但我的测试证明这是不正确的。

我能够使您的示例正常工作的唯一方法是将错误页面代码修改为以下内容:

[Route("Error/ServerError")]
public IActionResult ServerError()
{
    return View("Error/ServerError");
}

假设存在以下内容:[ProjectDir]\Views\Shared\Error\ServerError.cshtml

如果您将视图名称简单地设置为 "ServerError" 并且您的视图位于 [ProjectDir]\Views\Shared\ServerError.cshtml,则 Microsoft.AspNet.Diagnostics 或Microsoft.AspNet.Mvc 包。

当发出错误请求时,以下内容将写入日志:

info: Microsoft.AspNet.Mvc.Controllers.ControllerActionInvoker[1]
      Executing action method WebApplication2.Controllers.ErrorsController.Get with arguments () - ModelState is Valid'
fail: Microsoft.AspNet.Mvc.ViewFeatures.ViewResultExecutor[0]
       The view 'ServerError' was not found. Searched locations: /Views/Errors/ServerError.cshtml, /Views/Shared/ServerError.cshtml
fail: Microsoft.AspNet.Diagnostics.ExceptionHandlerMiddleware[0]
      An exception was thrown attempting to execute the error handler.
      System.InvalidOperationException: The view 'ServerError' was not found. The following locations were searched:
      /Views/Errors/ServerError.cshtml
      /Views/Shared/ServerError.cshtml.

日志清楚地指出试图在 /Views/Shared/ServerError.cshtml 找到视图。然而请求失败并使用默认错误处理程序。

此问题已记录在 aspnet/Diagnostics github 存储库 here