• webapi的几种过滤器


    好久没有写博客了 今天就来聊聊asp.net webapi的过滤器们

    过滤器主要有这么几种

    AuthorizationFilterAttribute 权限验证

    ActionFilterAttribute 日志 参数验证等

    ExceptionFilterAttribute 异常处理捕获

    我是如何使用这些过滤器的,最近在做项目中,这几种过滤器我都使用了,实现当别人调用接口的时候,首先验证权限,这个验证信息可以从Head里取也可以从Body里取,然后就是验证参数的有效性,参数需要后台验证,在实体里我都是定义了验证特性,拦截器正好根据这些特性统一做后台验证,所以我的后台数据验证统一在这一步就做完了,如果不符合直接抛出给客户端,然后还可以写日志,最后是异常的捕获,异常拦截器统一捕获异常,我在其它层就不要额外的做异常处理(事务方法除外,事务需要捕获异常回滚)

    这些过滤器 作为全局过滤器直接配置好 不用每个api controller都去声明特性

        /// <summary>
        /// 接口的权限验证
        /// Token身份验证,只有合法的用户才可以访问  否则会转向到登录页面或者无权限提示页面
        /// </summary>
        public class AuthGlobalAttribute : AuthorizationFilterAttribute
        {
            public string Roles { get; set; }
    
            public string Users { get; set; }
    
            public override void OnAuthorization(HttpActionContext actionContext)
            {
                if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
                {
                    return;
                }
                string controllerName = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                string actionName = actionContext.ActionDescriptor.ActionName;
                HttpContextBase context = (HttpContextBase)actionContext.Request.Properties["MS_HttpContext"];//获取传统context
                HttpRequestBase request = context.Request;//定义传统request对象 
                if (request["Token"] == null && actionContext.Request.Headers.Authorization == null)
                {
                    Result result = new Result { Flag = false, Message = "缺少Token身份信息", Code="203" };
                    HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
                    httpResponseMessage.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json");
                    httpResponseMessage.StatusCode = HttpStatusCode.BadRequest;
                    actionContext.Response = httpResponseMessage;
                    return;
                }
                //参数带有Token
                string token = request["Token"];
                token = (token ?? actionContext.Request.Headers.Authorization.Parameter);
    
                //根据Token获取当前用户上下文
                if (UserCache.Cache.Get(token) != null)
                {
                    HttpContext.Current.Items["User"] = UserCache.Cache.Get(token);
                    //获取用户上下文后 根据Roles属性比对过滤器角色 如果没有权限向外面抛401
                }
                else
                {
                    Result result = UserBLL.GetUserByToken(token);
                    HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
                    httpResponseMessage.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json");
                    httpResponseMessage.StatusCode = HttpStatusCode.BadRequest;
                    actionContext.Response = httpResponseMessage;
                    //actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("您无权限访问"));
                    return;
                }
                base.OnAuthorization(actionContext);
            }
    
    
        }
        /// <summary>
        /// 全局参数验证实体
        /// </summary>
        public class ValidateGlobalAttribute : ActionFilterAttribute
        {
            /// <summary>
            /// 所有实体参数接口 全局验证
            /// </summary>
            /// <param name="filterContext"></param>
            public override void OnActionExecuting(HttpActionContext filterContext)
            {
                if (!filterContext.ModelState.IsValid)
                {
                    ValidateResults vresult = new ValidateResults();
                    foreach (string key in filterContext.ModelState.Keys)
                    {
                        if (filterContext.ModelState[key].Errors.Count > 0)
                        {
                            vresult.ErrorResults.Add(new ValidateResult
                            {
                                IsValid = false,
                                MemberName = key,
                                ErrorMessage = filterContext.ModelState[key].Errors[0].ErrorMessage
                            });
                        }
                    }
                    Result<ValidateResults> result = new Result<ValidateResults> { Flag = false, Message = "数据验证失败", ResultObj = vresult,Code="208" };
                    HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
                    httpResponseMessage.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json");
                    httpResponseMessage.StatusCode = HttpStatusCode.BadRequest;
                    filterContext.Response = httpResponseMessage;
                    return;
                   // throw new HttpResponseException(oHttpResponseMessage);
                }
                base.OnActionExecuting(filterContext);
            }
    
        }
        /// <summary>
        /// 异常全局处理
        /// </summary>
        public class ExceptionGlobalAtrribute : ExceptionFilterAttribute
        {
            public override void OnException(HttpActionExecutedContext filterContext)
            {
                if (filterContext.Exception != null)
                {
                    string controllerName = filterContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                    string actionName = filterContext.ActionContext.ActionDescriptor.ActionName;
                    HttpContextBase context = (HttpContextBase)filterContext.Request.Properties["MS_HttpContext"];//获取传统context
                    HttpRequestBase request = context.Request;//定义传统request对象 
                    string token = string.Empty;
                    if (request["Token"] != null || filterContext.Request.Headers.Authorization != null)
                    {
                        token = request["Token"];
                        token = (token ?? filterContext.Request.Headers.Authorization.Parameter);
                    }
                    //获取当前用户上下文
                    UserContext user = UserCache.Cache.Get(token);
                    string description = filterContext.Exception.Message.ToString();
                    //int autokey = DaoPack.Sys_UserLogDao.GetMax<int>(m => m.AutoKey) + 1;
    
                    Sys_UserLog log = new Sys_UserLog
                    {
                        //AutoKey = autokey,
                        ActionName = controllerName + "/" + actionName,
                        Description = description,
                        UserID = user == null ? null : (int?)user.UserID,
                        UserName = user == null ? null : user.UserName,
                        Url = request.RawUrl,
                        ClientIP=SysService.GetHostAddress()
                    };
                    DaoPack.Sys_UserLogDao.Insert(log);
                }
                HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
                Result result = new Result { Flag = false, Message = "接口异常",Code="400" };
                httpResponseMessage.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json");
                httpResponseMessage.StatusCode = HttpStatusCode.BadRequest;
                filterContext.Response = httpResponseMessage;
                return;
                //throw new HttpResponseException(oHttpResponseMessage);
                // base.OnException(filterContext);
    
            }
        }
  • 相关阅读:
    C# 以GZip解压缩
    C# 获取时间戳(支持毫秒)
    C#中 DateTime 转 DateTimeOffset
    C# WPF中 SecureString 转 String
    C# 根据文件头判断文件类型
    C#中 MD5 32位加密
    C#中 Stream转为byte[]
    C#中byte[]转BitmapImage
    sql按天分组
    eclispe报错PermGen space
  • 原文地址:https://www.cnblogs.com/njcxwz/p/7170285.html
Copyright © 2020-2023  润新知