.netcore中的Filter是什么
过滤器是指在netcore的请求处理管道中运行指定的代码逻辑。例如指定身份验证,异常处理、盗链验证等等。过滤器其实是实现了AOP,我们可以通过过滤器实现额外的附加操作而不会影响实际的业务逻辑实现。
.netcore中的过滤器主要有以下几种
- Authorization Filter ----授权认证过滤器
- Resource Filter ----资源过滤器
- Action Filter ----Action过滤器
- Exception Filter ----异常过滤器
- Result Filter ----结果过滤器
Filter的执行顺序
各类Filter的实现示例
1、Authorization Filter:一般用于鉴权认证。如果认证不通过则直接返回(不过现在很多情况下都是使用鉴权中心进行验证的(例如Id4实现的用户中心),很少再需要实现Authorization Filter了,当然也有特例,这要根据实际业务而定)。
示例
1 /// <summary> 2 /// 自定义鉴权认证过滤器 3 /// </summary> 4 public class CustomerAuthorizationFilterAttribute : Attribute, IAsyncAuthorizationFilter,IOrderedFilter 5 { 6 public int Order { get; set; } = 0; 7 8 /// <summary> 9 /// 10 /// </summary> 11 /// <param name="context"></param> 12 /// <returns></returns> 13 public async Task OnAuthorizationAsync(AuthorizationFilterContext context) 14 { 15 var authFlag = false; 16 var descriptor = context.ActionDescriptor as ControllerActionDescriptor; 17 if (descriptor != null) 18 { 19 authFlag = descriptor.ControllerTypeInfo.GetCustomAttributes(true).OfType<DescriptionAttribute>().Any() 20 || descriptor.MethodInfo.GetCustomAttributes(true).OfType<DescriptionAttribute>().Any(); 21 } 22 if (authFlag) 23 { 24 string userId = context.HttpContext.User.Claims.FirstOrDefault(p => p.Type == "Subject")?.Value; 25 ISimpleUserService simpleUserService = context.HttpContext.RequestServices.GetService<ISimpleUserService>(); 26 var checkAuthResult = await CheckAuth(userId, simpleUserService); 27 if (checkAuthResult == false) 28 { 29 var responseModel = new ApiResponseModel<object>() 30 { 31 Code = "E000999", //自定义错误编码 32 Message = "NO PERMISSIONS", 33 }; 34 context.Result = new OkObjectResult(responseModel); //根据实际业务定义返回结果,可以是OkObjectResult,也可以是其他(例如UnauthorizedObjectResult) 35 //context.Result = new UnauthorizedObjectResult(responseModel); 36 return; 37 } 38 } 39 40 } 41 /// <summary> 42 /// 鉴权 43 /// </summary> 44 /// <param name="userId"></param> 45 /// <param name="userService"></param> 46 /// <returns></returns> 47 private async Task<bool> CheckAuth(string userId, ISimpleUserService userService) 48 { 49 //TODO Check authorization //var user= await userService.GetUserBydIdAsync(userId); 50 await Task.Delay(0); 51 return true; 52 } 53 }
2、ResourceFilter:一般用于对资源型信息进行过滤。常用于防盗链/资源缓存(根据判断缓存中是否存在当前资源,存在则直接返回)。
它分为执行前,执行后的实现。
执行前(OnResourceExecuting):在Authorization Filter执行完成后。
执行后(OnResourceExecuted):在Result Execution之后
示例:
1 /// <summary> 2 /// 自定义Resource Filter 3 /// </summary> 4 public class CustomerResourceFilter : Attribute, IResourceFilter 5 { 6 /// <summary> 7 /// 执行后 8 /// </summary> 9 /// <param name="context"></param> 10 public void OnResourceExecuted(ResourceExecutedContext context) 11 { 12 //无
13 } 14 /// <summary> 15 /// 执行前 16 /// </summary> 17 /// <param name="context"></param> 18 public void OnResourceExecuting(ResourceExecutingContext context) 19 { 20 #region 防盗链 --特别是一些文件,图片信息时 21 string urlReferrer = context.HttpContext.Request.Headers["Referer"]; 22 if (string.IsNullOrWhiteSpace(urlReferrer))//直接访问 23 { 24 context.Result = new ForbidResult(); 25 } 26 else if (!urlReferrer.Contains("localhost"))//非当前域名 27 { 28 context.Result = new ForbidResult(); 29 } 30 #endregion 31 #region 缓存信息 32 //从缓存读取信息 33 IMemoryCache cache = context.HttpContext.RequestServices.GetService<IMemoryCache>(); 34 //请求路径作为缓存的Key 35 string path = context.HttpContext.Request.Path.ToString(); 36 object value = null; 37 if (cache.TryGetValue(path, out value)) 38 { 39 string result = value.ToString(); 40 //如果有Result,则不会往执行后面的过滤器 41 context.Result = new ContentResult() { Content = result }; 42 } 43 #endregion 44 } 45 }
3、Action Filter :执行过滤器,一般是在Action执行前后进行过滤。可以通过这个Filter进行一些参数验证逻辑,也可以通过这个filter记录操作日志信息。
它分为执行前,执行后的实现。
执行前(OnActionExecuting):在Action执行之前。
执行后(OnActionExecuted):在Action执行完成之后。
需要注意的是:ActionFilter are not supported in Razor Pages.(Action Filter 不支持Razor Pages)
示例:
1 /// <summary> 2 /// 自定义Action Filter 3 /// </summary> 4 public class CustomerActionFilter : Attribute, IActionFilter 5 { 6 private readonly ILogger _logger; 7 public CustomerActionFilter(ILogger<CustomerActionFilter> logger) 8 { 9 this._logger = logger; 10 } 11 /// <summary> 12 /// 执行后 13 /// </summary> 14 /// <param name="context"></param> 15 public void OnActionExecuted(ActionExecutedContext context) 16 { 17 string userId = context.HttpContext.User.Claims.FirstOrDefault(p => p.Type == "Subject")?.Value; 18 19 var descriptor = context.ActionDescriptor as ControllerActionDescriptor; 20 if (descriptor != null) 21 { 22 string message = $"{descriptor.ControllerName}--{descriptor.ActionName} excecuted by {userId} at {DateTime.UtcNow.ToLongDateString()}"; 23 _logger.LogInformation(message); 24 25 } 26 } 27 /// <summary> 28 /// 执行前 29 /// </summary> 30 /// <param name="context"></param> 31 public void OnActionExecuting(ActionExecutingContext context) 32 { 33 string userId = context.HttpContext.User.Claims.FirstOrDefault(p => p.Type == "Subject")?.Value; 34 35 var descriptor = context.ActionDescriptor as ControllerActionDescriptor; 36 if (descriptor != null) 37 { 38 string message = $"{descriptor.ControllerName}--{descriptor.ActionName} excecuting by {userId} at {DateTime.UtcNow.ToLongDateString()}"; 39 _logger.LogInformation(message); 40 41 } 42 } 43 }
4、Exception Filter :异常过滤器,用于捕获未处理的异常信息。
示例:
1 /// <summary> 2 /// global exception filter 3 /// </summary> 4 public class GlobalExceptionFilter : Attribute, IAsyncExceptionFilter 5 { 6 private readonly ILogger _logger; 7 /// <summary> 8 /// 9 /// </summary> 10 /// <param name="logger"></param> 11 public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger) 12 { 13 this._logger = logger; 14 } 15 /// <summary> 16 /// 17 /// </summary> 18 /// <param name="context"></param> 19 /// <returns></returns> 20 public async Task OnExceptionAsync(ExceptionContext context) 21 { 22 this._logger.LogError($"在响应 {context.HttpContext.Request.Path} 时出现异常,信息:{context.Exception.Message}"); 23 24 if (!context.ExceptionHandled) //异常未被处理 25 { 26 //if (this.IsAjaxRequest(context.HttpContext.Request))//ajax请求 27 //{ 28 var result= new ApiResponseModel<object>() 29 { 30 Code = "E9999999", 31 Message = "系统发生错误,请联系管理员", 32 33 }; 34 context.Result = new BadRequestObjectResult(result);//中断---请求到这里结束了,不在往下执行Action 35 //} 36 //else 37 //{ 38 // var result = new ViewResult { ViewName = "~/Views/Shared/Error.cshtml" }; 39 // result.ViewData = new ViewDataDictionary(_modelMetadataProvider, 40 // context.ModelState); 41 // result.ViewData.Add("Exception", context.Exception.Message); 42 // context.Result = result; 43 //} 44 context.ExceptionHandled = true;//异常已被处理 45 } 46 } 47 private bool IsAjaxRequest(HttpRequest request) 48 { 49 string header = request.Headers["X-Requested-With"]; 50 return "XMLHttpRequest".Equals(header); 51 } 52 }
5、Result Filter: 结果过滤器,例如可以对结果进行格式化、大小写转换,附件特定返回信息等操作。(格式化其实可以通过在startup中指定,ResultFilter较少使用)
示例
1 /// <summary> 2 /// 自定义ResultFilter 3 /// </summary> 4 public class CustomerResultFilter : Attribute, IResultFilter 5 { 6 7 public void OnResultExecuting(ResultExecutingContext context) 8 { 9 var headerName = "NextToken"; 10 context.HttpContext.Response.Headers.Add( 11 headerName, new string[] { "xxxxxxx" }); 12 //TODO如果访问过于频繁返回Too Many Request 13 } 14 15 public void OnResultExecuted(ResultExecutedContext context) 16 { 17 //无 18 } 19 20 }
Filter的注册
1、特性标识
1-1、指定对应的Filter特性(可以是Controller上标注也可以是指定的Action)
例如
1 [Route("api/[controller]")] 2 [ApiController] 3 [CustomerAuthorizationFilter] 4 public class ProductController : ControllerBase 5 { 6 ..... 7 }
1-2、ServiceFilter和TypeFilter
为什么会有ServcieFilter和TypeFilter来指定呢?因为Filter可能存在有参的构造函数(它的参数可能是由netcore的DI框架注入的或者其它的,此时就不能像1-1中通过Filter属性直接标识了,只能通过ServiceFilter或者TypeFilter进行标注)。它们之间的区别主要是:
- ServiceFilter检索来自DI过滤器的一个实例。使用ServiceFilter而不注册过滤器类型会导致异常(即必须在startup中添加对应Filter的服务)。
- TypeFilterAttribute非常类似于ServiceFilterAttribute(和还实现IFilterFactory),但其类型不从DI容器直接解决。它使用的是Microsoft.Extensions.DependencyInjection.ObjectFactory实例化类型(对应的Filter无需注册到DI中)。
2、全局注册
在startup--ConfigureServices(IServiceCollection services)中注册
1 services.AddMvc(options => 2 { 3 options.Filters.Add<CustomerActionFilter>(); 4 options.Filters.Add<CustomerAuthorizationFilterAttribute>(); 5 });
------------------------------------------
参考
https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-5.0
------
本文地址:https://www.cnblogs.com/johnyong/p/14408721.html