zoukankan      html  css  js  c++  java
  • .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;
    
               
            }
    
    
    
    
           
    
        }
    

      

  • 相关阅读:
    刷盘子的中国
    重温一些文章
    小心时间悄悄流失
    WebService笔记一
    JavaScript类型转换方法及需要注意的问题
    TSQL查询 点滴 1
    介绍几款浏览器兼容性测试工具
    [推荐] jQuery 表格插件汇总
    学会总结,学会关注细节,学会拥有一颗平静的心。
    Open Source Web Design!
  • 原文地址:https://www.cnblogs.com/KQNLL/p/11644514.html
Copyright © 2011-2022 走看看