webapi使用过滤器拦截客户端传来的参数

项目是前端和后端分离的,想在服务器上拦截客户端传上来的参数,然后做进一步处理,如:权限,验证是否登录,或者其他的

1.添加新类:OperationAttribute,用来做权限验证的

代码如下:

 /// <summary>
    /// 判断是否有权限访问某操作
    /// </summary>
    public class OperationAttribute:ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var parmethod = actionContext.Request.Method;
            string method = parmethod.Method;
            dynamic model = CommonTools.SessionHelper.GetSession("UserInfo");
            int UserId = model.UserId;
            int IsSuper = model.IsSuper;
            string ActionLogo = "";
            if (method.ToLower() == "post")//post提交的时候
            {
                //post提交的参数
                var task = actionContext.Request.Content.ReadAsStreamAsync();
                var content = string.Empty;
                using (Stream sm = task.Result)
                {
                    sm.Seek(0, SeekOrigin.Begin);//设置流的开始位置
                    var bytes = sm.ToByteArray();
                    content = bytes.ToStr();//此处就是客户端出来的参数
                }
                dynamic obj = CommonTools.JsonHelper.DeserializeJsonToObject<dynamic>(content);//序列化为对象
                ActionLogo = obj.ActionLogo == null ? "" : obj.ActionLogo;//获取前端传过来的动作标识
            }
            else
            {
                //get提交获取参数
                var qs = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);
                if (qs.Count > 0)
                {
                    string[] keys = qs.AllKeys;
                    if (keys.Contains("ActionLogo"))
                    {
                        ActionLogo = qs["ActionLogo"];
                    }
                }
            }
            IsVisit(UserId, IsSuper, ActionLogo, actionContext);//开始验证
        }

        public void IsVisit(int UserId, int IsSuper, string ActionLogo, HttpActionContext actionContext)
        {
            if (IsSuper == 1)//超级管理员不需要验证
            {
                base.OnActionExecuting(actionContext);
            }
            else
            {
                if (ActionLogo =="")
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.InternalServerError, new
                    {
                        code = "1",
                        data = "",
                        message = "您无权限进行此操作"
                    });
                }
                else
                {
                    //进行下一步判断
                }
            }
        }
    }

2.添加一个公共类,用来处理post参数

public static class Common 
    {
        /// <summary>
        /// 转为byte数组
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static byte[] ToByteArray(this Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }

        /// <summary>
        /// 转为字符串
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        public static string ToStr(this byte[] arr)
        {
            return Encoding.Default.GetString(arr);
        }
        
    }

之所以要这样写,是为了防止过滤器重叠的时候,post提交获取不到参数。

写好过滤类之后,直接在方法,或者控制器上使用,

[Operation]加在方法上,就可以验证方法的权限,加在控制器上,就可以验证控制器下所有的方法,若在控制中有不需要验证的方法,可以在OnActionExecuting上加上:

if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
{
return;
},

然后在不需要验证的方法上调用[AllowAnonymous],

如登录方法:

 [AllowAnonymous]
        [HttpGet]
        public HttpResponseMessage Login(string UserName, string UserPwd)
        {
            string jsonresult = "";
            List<object> OperationResult = db.Login(UserName, UserPwd);
            switch (OperationResult[0].ToString())
            {
                case "0":
                    jsonresult = "{\"State\":0,\"err\":\"10001\",\"info\":\"登录出错\"}";
                    break;
                case "-1":
                    jsonresult = "{\"State\":0,\"err\":\"10002\",\"info\":\"密码错误\"}";
                    break;
                case "-2":
                    jsonresult = "{\"State\":0,\"err\":\"10003\",\"info\":\"用户名不存在\"}";
                    break;
                default:
                    User model = (User)OperationResult[1];
                    CommonTools.SessionHelper.SetSession("UserInfo",model);
                    jsonresult = "{\"State\":1,\"err\":\"10000\",\"info\":\"登录成功\",\"LoginInfo\":{\"UserInfo\":{\"UserName\":\"" + model.UserName + "\",\"UserId\":" + model.UserId + "}";
                    string jsonstr = OperationResult[2].ToString();
                    jsonresult += ",\"MenuInfo\":" + jsonstr;
                    jsonresult += "}}";
                    break;
            }
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(jsonresult, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }

这样登录的方法就绕过了验证

posted @ 2019-08-20 23:24  一夜听春雨  阅读(1190)  评论(0编辑  收藏  举报