【问题标题】:ASP.NET Core 2 MVC Global Exception Handling not workingASP.NET Core 2 MVC 全局异常处理不起作用
【发布时间】:2018-09-11 22:39:39
【问题描述】:

我目前正在开发一个 ASP.NET Core 2 MVC 应用程序。我试图弄清楚Startup.cs 中的全局异常处理是如何工作的。

到目前为止一切顺利,我可以使用常规的app.UseStatusCodePages() 中间件。

尽管如此,当我尝试使用 app.UseStatusCodePagesWithReExecute 在视图上显示 HTTP 状态代码时,我只得到一个标准的 HTTP 500 页面,并且在我的错误控制器中没有重定向到我的 CustomError 操作。

出于演示目的,我在生产环境中运行我的应用程序,而不是在开发环境中。

我在我的 ValuesController 中抛出了我的错误。 ValuesController 看起来像这样:

public class ValuesController : Controller
{
    public async Task<IActionResult> Details(int id)
    {
        throw new Exception("Crazy Error occured!");
    }
}

我的Startup.cs 看起来像这样:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Global Exception Handling, I run in Production mode
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else // I come into this branch
    {
        //app.UseExceptionHandler("/Error/Error");

        // My problem starts here: I cannot redirect to my custom error method... 
        //there is only a standard http 500 screen
        app.UseStatusCodePagesWithReExecute("/Error/CustomError/{0}");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Values}/{action=Index}/{id?}");
    });
}

最后,我的 ErrorController 看起来像这样:

public class ErrorController : Controller
{
    public IActionResult CustomError(string code)
    {
        // I only want to get here in debug, to get the code
        // unfortunately it never happens :/
        return Content("Error Test");
    }
}

很遗憾,我无法重定向到我的 CustomError 方法并根据异常获取 HTTP 状态码。

只有一个标准的 chrome HTTP 500 页面,因此没有任何作用。

【问题讨论】:

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


    【解决方案1】:

    状态代码页中间件在管道执行期间无法处理未处理的异常,但会检查 响应 状态代码(对于没有正文的响应)。

    如果你把action方法修改成这样,你会得到自定义的错误页面:

     public async Task<IActionResult> Details(int id)
     {
        return new StatusCodeResult(500);
     }
    

    对于异常处理,请查看UseExceptionHandler 方法。例如:

    app.UseExceptionHandler("/Error/CustomError/500");
    

    请注意,您可以在应用中同时使用 UseExceptionHandlerUseStatusCodePagesWithReExecute

    【讨论】:

    • 谢谢,当我返回 StatusCodeResult 时它工作得很好......嗯,但是我如何在不使用 MVC 中的 try catch 的情况下捕获运行时异常? :)
    • @TimHorton 如果您只想在 MVC 中间件中捕获异常,请使用 Exception Filter。如果对于所有管道异常,则使用另一个版本的 ExceptionHandler:app.UseExceptionHandler(errorApp =&gt; { errorApp.Run(async context =&gt; ... ) }(请查看 this SO post 以获取示例)。当然,你总是可以为全局 try-catch 编写自己的中间件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2016-02-12
    • 2021-12-26
    相关资源
    最近更新 更多