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

时间:2016-02-05 19:08:01

标签: 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();
}

错误页码:

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

错误页面视图:

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

请注意,“找不到页面”错误会被发送到/Error/PageNotFound而没有任何问题,只是其他错误没有。

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

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

1 个答案:

答案 0 :(得分:1)

我原本以为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上。

相关问题