zoukankan      html  css  js  c++  java
  • 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;
            }
  • 相关阅读:
    全国(省,直辖市,自治区,特别行政区)映射集合
    数据库辅助类
    时间格式化工具类
    密码加密(MD5)
    算法竞赛入门经典——第3章答案
    第三章学习小结—-转
    isalpha函数和isdigit函数
    重新实现库函数
    树状数组总结——转
    线段树——转
  • 原文地址:https://www.cnblogs.com/jonney-wang/p/11352373.html
Copyright © 2011-2022 走看看