我已经实现了以下操作过滤器来处理 ajax 错误:
public class HandleAjaxCustomErrorAttribute : ActionFilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest()) return;
filterContext.Result = AjaxError(filterContext.Exception.Message, filterContext);
//Let the system know that the exception has been handled
filterContext.ExceptionHandled = true;
}
}
我希望过滤器能够仅捕获某些类型的错误,并在 Controller 操作中像这样使用它:
[HandleAjaxCustomErrorAttribute(typeof(CustomException))]
public ActionResult Index(){
// some code
}
怎么会发生这种事?谢谢!
最佳答案
我想您正在寻找这个:http://msdn.microsoft.com/en-us/library/aa288454%28v=vs.71%29.aspx#vcwlkattributestutorialanchor1
要为属性提供参数,您可以创建非静态属性或使用构造函数。在你的情况下,它看起来像这样:
public class HandleAjaxCustomErrorAttribute : ActionFilterAttribute, IExceptionFilter
{
private Type _exceptionType;
public void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception.GetType() != _exceptionType) return;
if (!filterContext.HttpContext.Request.IsAjaxRequest()) return;
filterContext.Result = AjaxError(filterContext.Exception.Message, filterContext);
//Let the system know that the exception has been handled
filterContext.ExceptionHandled = true;
}
public HandleAjaxCustomErrorAttribute(Type exceptionType)
{
_exceptionType = exceptionType;
}
}
关于asp.net-mvc-3 - 自定义 ErrorHandling 操作过滤器,仅捕获特定类型的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17806299/