.net core action过滤器的普通应用
.net core action过滤器有很多用途,比如特别是全局数据拦截操作。这里举两个例子。
1、使用ActionFilterAttribute全局过滤日志。
/// <summary> /// 请求参数日志过滤器 /// </summary> public class ParameterLogFilterAttribute : ActionFilterAttribute { /// <summary> /// 不需要记录日志的path /// </summary> List<string> paths = new List<string>() { "/api/Oauth/Login" }; public override void OnActionExecuting(ActionExecutingContext filterContext) { var path= filterContext.HttpContext.Request.Path; if (paths.Contains(path)) return; var type = filterContext.HttpContext.Request.Method; var str = filterContext.ActionArguments.ToJson(); var ip = filterContext.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(); LogHelper.WriteLog($"日志过滤器自动请求日志:【IP:{ip}】【请求方式:{type}】---->{path}---->{str}"); } public override void OnActionExecuted(ActionExecutedContext context) { var path = context.HttpContext.Request.Path; var type = context.HttpContext.Request.Method; if (type.ToUpper() == "GET") return; var ip = context.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(); var str = context.Result.ToJson(); LogHelper.WriteLog($"日志过滤器自动结果日志:【IP:{ip}】【请求方式:{type}】---->{path}---->{str}"); } }
2、全局自定义验证过滤器
public class CentrizenTokenFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var test = filterContext.HttpContext.Request.Path; string bearer = filterContext.HttpContext.Request.Headers["Authorization"].FirstOrDefault(); if (string.IsNullOrEmpty(bearer)|| !bearer.Contains("Bearer")) return; string[] jwt = bearer.Split(' '); var tokenObj = new JwtSecurityToken(jwt[1]); var claimsIdentity = new ClaimsIdentity(); claimsIdentity.AddClaims(tokenObj.Claims); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); Thread.CurrentPrincipal = claimsPrincipal; filterContext.HttpContext.User = claimsPrincipal; } }