ASP.Net MVC使用操作过滤器属性进行错误处理 [英] ASP.Net MVC Error handling using Action Filters Attributes
问题描述
我正在尝试使用操作过滤器属性按照ScottGu的博客
我的代码如下:
[HandleError]
[HandleError(ExceptionType = typeof(NullReferenceException),View =CustomError)]
public class ArticlesController:Controller
{
public object OhDearACrash()
{
throw new Exception(哦亲爱的);
}
public object NullRefCrash()
{
throw new NullReferenceException();
}
我遇到一个我无法打到CustomError视图的问题当异常被抛出时,我收到异常
OhDearACrash:用户代码未处理异常
NullRefCrash:NullReferenceException被用户代码
未处理,因此未处理的异常由默认[HandleError]拾取,它将路由到处理错误的View / Shared / Error.aspx。 / p>
如何处理未处理的异常?
一个一个执行。在您的情况下,问题可能是在特定的HandleError操作过滤器之前执行。
您可以通过设置Order属性来影响执行顺序的操作过滤器:
[HandleError(Order = 2)]
[HandleError(Order = 1,ExceptionType = typeof(NullReferenceException),View =CustomError)]
public class ArticlesController:Controller
{
}
I am trying to implement Error handling using Action Filters Attributes as per ScottGu's blog
My code is as follows:
[HandleError]
[HandleError(ExceptionType = typeof(NullReferenceException), View = "CustomError")]
public class ArticlesController : Controller
{
public object OhDearACrash()
{
throw new Exception("Oh Dear");
}
public object NullRefCrash()
{
throw new NullReferenceException();
}
I am encountering an issue where I am never able to hit the CustomError view as I receive an exception when the exception is thrown
OhDearACrash: Exception was unhandled by user code
NullRefCrash: NullReferenceException was unhandled by user code
and so the unhandled exception is picked up by the Default [HandleError] which routes to View/Shared/Error.aspx which handles the error.
How do I handle the unhandled exception?
The action filters are executed one by one. In your case, the problem is probably that the generic HandleError action filter is executed before the specific one.
You can influence the order of execution by setting the 'Order' property of your action filter:
[HandleError(Order = 2)]
[HandleError(Order = 1, ExceptionType = typeof(NullReferenceException), View = "CustomError")]
public class ArticlesController : Controller
{
}
这篇关于ASP.Net MVC使用操作过滤器属性进行错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!