【问题标题】:Accessing the exception if custom redirection redirects to a controller如果自定义重定向重定向到控制器,则访问异常
【发布时间】:2012-10-19 17:29:29
【问题描述】:

我正在使用 MVC4,并且希望能够从控制器中抛出 HttpExceptions,并在单独的控制器中处理这些异常。

我为此设置了<customErrors mode="On" defaultRedirect="/Error"/>。这可行,但在我的控制器中,我希望能够访问异常。

最好有两种模式:

  1. 处理 HttpException 的实例,这样我就可以从控制器抛出一个 HttpException 并对其进行相应的处理

  2. 处理所有其他错误。

在第一种情况下,我想向用户代理提供适当的状态代码,可能还有一个视图。在第二种情况下,我想向用户代理显示状态 500,并显示带有可选消息的默认视图。

为此,我认为我需要访问异常数据 - 至少,我想不出任何其他合适的方法来做到这一点。

设置的正确方法是什么?我知道关于 MVC 中的错误处理还有很多其他问题,但似乎没有人回答这些问题。

【问题讨论】:

标签: asp.net-mvc http error-handling


【解决方案1】:
 but in my controller I would like to be able to access the exception.

你试过Server.GetLastError:

Exception ex = Server.GetLastError();

Server.GetLastError() - 应该在 global.asax 中的 Application_Error 中使用,在这种情况下你可以像described here 这样处理最后一个错误,此外你应该删除

filters.Add(new HandleErrorAttribute());

在 FilterConfig.cs 中

更多信息请看:

Application_Error not firing when customerrors = "On"

ASP.NET custom error page - Server.GetLastError() is null

http://www.secretgeek.net/custom_errors_mvc.asp

http://devstuffs.wordpress.com/2010/12/12/how-to-use-customerrors-in-asp-net-mvc-2/

【讨论】:

  • 唉,Server.GetLastError 返回null
猜你喜欢
  • 1970-01-01
  • 2018-10-06
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多