业务需求,拦截器验证每个请求inputstream(实际是application/json流)的数据,但是json反序列化实体格式不同。
/// <summary> /// 递归验证以application/json方式post上来的stream格式数据 /// </summary> /// <param name="jo"></param> /// <returns></returns> protected string ChkJson(JProperty jo) { if (jo.HasValues && jo.Count > 1) { foreach (JProperty item in jo) { return ChkJson(item); } } else { string msg = ""; string val = jo.Value.ToString(); if (IsContainXSSCharacter(val , out msg)){ return msg; } } return ""; }
using (System.IO.StreamReader sr = new System.IO.StreamReader(inputStream)) { try { Newtonsoft.Json.Linq.JObject jo = Newtonsoft.Json.Linq.JObject.Parse(sr.ReadToEnd()); if (jo.HasValues) foreach (JProperty item in jo.Properties()) { var tmpMsg = ChkJson(item); if (!string.IsNullOrEmpty(tmpMsg)) { Content.Content = tmpMsg; filterContext.Result = Content; filterContext.HttpContext.Response.StatusCode = 801; filterContext.HttpContext.Response.StatusDescription = "sensitive information"; return; } } } catch (System.Exception err) { // 有时候前端提交的application/json 并不是一段正常的json,不再处理xss注入 } }
Newtonsoft.Json.Linq.JObject 遍历验证每个属性内容
原文:https://www.cnblogs.com/jonney-wang/p/11352373.html