我已实现以下操作过滤器来处理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
}
这怎么可能发生?谢谢!
答案 0 :(得分: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;
}
}