2

我已经实现了以下操作过滤器来处理 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;
        }
    }

我希望过滤器能够仅捕获某些类型的错误并在控制器操作中像这样使用它:

[HandleAjaxCustomErrorAttribute(typeof(CustomException))]
public ActionResult Index(){
 // some code
}

这怎么可能发生?谢谢!

4

1 回答 1

4

我认为你正在寻找这个: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;
    }
}
于 2013-07-23T12:04:45.303 回答