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

            var req = filterContext.RequestContext.HttpContext.Request;
if (req.ContentType.ToLower().Contains("application/json") && req.InputStream.Length > )
{
System.IO.Stream stm = new MemoryStream();
req.InputStream.CopyTo(stm);
stm.Position = ;
req.InputStream.Position = ;
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 != )
{
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 ;
if (jo.HasValues && jo.Values().Count() > )
{
foreach (JToken item in jo.Values())
{
var result = ChkJson(item, out msg);
if (result != )
return result;
}
}
else
{
string val = jo.ToString();
if (IsContainXSSCharacter(val , out msg)){
return ;
}
} return ;
}
05-14 10:51