Newtonsoft.Json.Linq.JObject 遍历验证每个属性内容

业务需求,拦截器验证每个请求inputstream(实际是application/json流)的数据,但是json反序列化实体格式不同。

            var req = filterContext.RequestContext.HttpContext.Request;
            if (req.ContentType.ToLower().Contains("application/json") && req.InputStream.Length > 0)
            {
                System.IO.Stream stm = new MemoryStream();
                req.InputStream.CopyTo(stm);
                stm.Position = 0;
                req.InputStream.Position = 0;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(stm))
                {
                    try
                    {
                        Newtonsoft.Json.Linq.JObject jo = Newtonsoft.Json.Linq.JObject.Parse(sr.ReadToEnd());
                        if (jo.HasValues)
                        {
                            foreach (JToken item in jo.Values())
                            {
                                var tmpMsg = "";
                                int ckResult = ChkJson(item, out tmpMsg);
                                if (ckResult != 0)
                                {
                                    Content.Content = tmpMsg;
                                    filterContext.Result = Content;
                                    filterContext.HttpContext.Response.StatusCode = ckResult;
                                    filterContext.HttpContext.Response.StatusDescription = "sensitive information";
                                    return;
                                }
                            }
                        }
                    }
                    catch (System.Exception)
                    {
                        // 若输入流不是json对象不再校验
                    }

                }
            }
        protected new int ChkJson(JToken jo, out string msg)
        {
            msg = "";
            if (jo == null) return 0;
            if (jo.HasValues && jo.Values().Count() > 0)
            {
                foreach (JToken item in jo.Values())
                {
                    var result = ChkJson(item, out msg);
                    if (result != 0)
                        return result;
                }
            }
            else
            {
                string val = jo.ToString();
                if (IsContainXSSCharacter(val , out msg)){
                    return 801;
                }
            }

            return 0;
        }

 

posted on 2019-08-14 15:42  jonney_wang  阅读(5562)  评论(0编辑  收藏  举报

导航