asp.net-mvc-3 - 自定义 ErrorHandling 操作过滤器,仅捕获特定类型的异常

标签 asp.net-mvc-3 asp.net-mvc-4

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

相关文章:

javascript - ng-click 在 MVC 部分 View 中不起作用

c# - 当我渲染局部 View 时,我的模型为空

jQuery Ajax 帖子将 null 发送到我的 MVC Controller

sql-server - 数据库第一个 Entity Framework 更新模型不起作用: What can be the reason?

asp.net-mvc - 在 Controller 操作方法中重用代码的最佳方法

.net - 在 MVC asp.net 中的客户端 PC 上完成下载后,如何删除文件

c# - 从 MVC 区域重定向将我重定向到顶级操作?

asp.net-mvc-3 - 从 Razor View 引用资源文件

c# - IHttpClientFactory 单例 .NET 框架

jquery - 使用 MVC 4 进行远程 jQuery 验证,动态验证以 loc? 开头的所有输入