ExceptionFilter asp.net mvc
本文关键字:mvc net asp ExceptionFilter | 更新日期: 2023-09-27 18:04:21
我将创建自己的exceptionfilter
,继承FilterAttribute
和IExceptionFilter
源代码如下:
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("Не может быть меньше нуля");
您必须在ASP中注册您的过滤器IndexException
。. NET MVC管道通过RegisterGlobalFilters
在 FilterConfig.cs
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("Не может быть меньше нуля");