gpt4 book ai didi

c# - ASP.NET Core 2 MVC 全局异常处理不起作用

转载 作者:行者123 更新时间:2023-11-30 23:03:57 29 4
gpt4 key购买 nike

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

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

然而,当我尝试使用 app.UseStatusCodePagesWithReExecute 在我的 View 中显示 HTTP 状态代码时,我只得到一个标准的 HTTP 500 页面并且没有重定向到我的 CustomError 我的错误 Controller 中的操作。

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

我在 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 页面,因此没有任何效果。

最佳答案

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

如果您将操作方法​​修改为类似这样的内容,您将获得自定义错误页面:

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

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

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

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

关于c# - ASP.NET Core 2 MVC 全局异常处理不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49615916/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com