繁体   English   中英

ExceptionFilter asp.net mvc

[英]ExceptionFilter asp.net mvc

我将创建自己的exceptionfilter ,它继承自FilterAttributeIExceptionFilter源代码如下:

public class IndexException : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext exceptionContext)
    {
        if (!exceptionContext.ExceptionHandled && exceptionContext.Exception is IndexOutOfRangeException)
        {
            exceptionContext.Result = new RedirectResult("/Content/ExceptionFound.html");
            exceptionContext.ExceptionHandled = true;
        }
    }
}

但是当我的代码到达Index方法时手动生成异常,我的过滤器无法工作

[IndexException]
public ActionResult Index()
{
    throw new Exception("Не может быть меньше нуля");

您必须通过FilterConfig.cs RegisterGlobalFilters在ASP.NET MVC管道中RegisterGlobalFilters过滤器IndexException

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        // add your filter
        filters.Add(new IndexException());
    }
}

如果捕获到IndexOutOfRangeException则您的异常过滤器将仅重定向到ExceptionFound.html在您提供的示例中,您将抛出一个通用Exception

更改过滤器以捕获所有类型的异常或更改此行:

throw new Exception("Не может быть меньше нуля");

对此:

throw new IndexOutOfRangeException("Не может быть меньше нуля");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM