Newtonsoft.Json.Linq.JObject 遍歷驗證每一個屬性內容

業務需求,攔截器驗證每一個請求inputstream(實際是application/json流)的數據,可是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;
        }
相關文章
相關標籤/搜索