• .net core action过滤器的普通应用


    .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;
    
               
            }
    
    
    
    
           
    
        }
    

      

  • 相关阅读:
    webpack指南(四)shimming
    webpack指南(三)缓存
    webpack指南(二)code spliting+懒加载
    webpack配置篇
    React组件setState
    React 生命周期
    React学习随笔
    @vue/cli 4.0+express 前后端分离实践
    @vue/cli 4.0.5 学习记录
    VMware Workstation 与 Device/Credential Guard 不兼容
  • 原文地址:https://www.cnblogs.com/KQNLL/p/11644514.html
Copyright © 2020-2023  润新知