【发布时间】: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