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

Mat*_*ete 6 asp.net-core-mvc

我的理解是,如果你添加app.UseExceptionHandler();并给它一个ASP.Net应该加载该页面的路径,当有一个错误没有被代码捕获但在我的情况下我仍然得到正常的"Http 500内部服务器错误"页面.我可以采取我给出的路径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();
}
Run Code Online (Sandbox Code Playgroud)

错误页码:

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

错误页面视图:

<p>
    @ViewData["ErrorMessage"]
</p>
Run Code Online (Sandbox Code Playgroud)

请注意,"找不到页面"错误被路由到/Error/PageNotFound没有问题,只是其他错误没有.

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

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

Cob*_*ter 1

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

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

[Route("Error/ServerError")]
public IActionResult ServerError()
{
    return View("Error/ServerError");
}
Run Code Online (Sandbox Code Playgroud)

假设存在以下内容:[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.
Run Code Online (Sandbox Code Playgroud)

该日志清楚地表明尝试在 /Views/Shared/ServerError.cshtml 中定位视图。然而请求失败并使用默认错误处理程序。

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