一、过滤器的优级依次介绍如下(逐次递减):
Authorization Filter -> Resource Filter -> Acton Filter -> Exception Filter -> Result Filter
1、Authorization Filter (权限过滤器)
/// <summary> /// 权限过滤器 /// </summary> public class GlobalAuthorizationFilter : Attribute, IAuthorizationFilter { /// <summary> /// 优化权最高的过滤器 /// </summary> /// <param name="context"></param> public void OnAuthorization(AuthorizationFilterContext context) { //context.Result = new ObjectResult("IAuthorizationFilter 过滤输出"); Console.WriteLine("IAuthorizationFilter 过滤输出"); } }
2、Resource Filter (资源过滤器)
/// <summary> /// 资源过滤器 /// </summary> public class GlobalResourceFilter : IResourceFilter { /// <summary> /// 获取资源后拦截 /// </summary> /// <param name="context"></param> public void OnResourceExecuted(ResourceExecutedContext context) { Console.WriteLine("IResourceFilter OnResourceExecuted 输出"); } /// <summary> /// 获取资源前拦截 /// </summary> /// <param name="context"></param> public void OnResourceExecuting(ResourceExecutingContext context) { Console.WriteLine("IResourceFilter OnResourceExecuting 输出"); } }
3、Acton Filter
/// <summary> /// Acion过滤器 /// </summary> public class GlobalActonFilter : Attribute, IActionFilter { /// <summary> /// Acion 执行后拦截 /// </summary> /// <param name="context"></param> public void OnActionExecuted(ActionExecutedContext context) { Console.WriteLine("IActionFilter OnActionExecuted Acion 执行后拦截"); } /// <summary> /// Acion 执行前拦截 /// </summary> /// <param name="context"></param> public void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine("IActionFilter OnActionExecuting Acion 执行前拦截"); } }
4、Exception Filter
/// <summary> /// 异常全局过滤器 /// </summary> public class GlobalExceptionFilter : IExceptionFilter { /// <summary> /// 异常处理 /// </summary> /// <param name="context">异常上下文</param> public void OnException(ExceptionContext context) { Console.WriteLine(context.Exception); //如果这里设为false,就表示告诉MVC框架,我没有处理这个错误。然后让它跳转到自己定义的错误页(设为true的话,就表示告诉MVC框架,异常我已经处理了。不需要在跳转到错误页了,也部会抛出黄页了) context.ExceptionHandled = false; } }
5、Result Filter
/// <summary> /// 结果过滤器 /// </summary> public class GlobalResultFilter : IResultFilter { /// <summary> /// 动作结果执行后 /// </summary> /// <param name="context"></param> public void OnResultExecuted(ResultExecutedContext context) { Console.WriteLine("IResultFilter OnResultExecuted Acion 动作结果执行后"); } /// <summary> /// 动作结果执行前 /// </summary> /// <param name="context"></param> public void OnResultExecuting(ResultExecutingContext context) { Console.WriteLine("IResultFilter OnResultExecuting Acion 动作结果执行前"); } }
原文地址:https://www.cnblogs.com/intotf/p/10189665.html
时间: 2024-10-10 17:16:21