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

      

  • 相关阅读:
    解决android模拟器太大,小屏幕无法完全显示的问题
    寡人写的第一个HTML5页面
    android开发环境重装系统之后的配置
    PHP程序的一次重构记录
    重构遗留代码(1):金牌大师
    java加密算法研究
    理解Java常量池
    由一个项目看java TCP/IP Socket编程
    java List分组和排序处理
    JAVA获取方法参数名的分析(一)
  • 原文地址:https://www.cnblogs.com/KQNLL/p/11644514.html
Copyright © 2011-2022 走看看