xss特性转义
public static class XSSHelper { /// <summary> /// XSS过滤 /// </summary> /// <param name="html">html代码</param> /// <returns>过滤结果</returns> public static string Filter(string html) { if (!string.IsNullOrWhiteSpace(html)) { html = System.Security.SecurityElement.Escape(html); } return html; } }
public class XSSFilterAttribute: ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { //获取Action参数集合 var ps = context.ActionDescriptor.Parameters; //遍历参数集合 foreach (var p in ps) { if (context.ActionArguments[p.Name] != null) { //当参数等于字符串 if (p.ParameterType.Equals(typeof(string))) { context.ActionArguments[p.Name] = XSSHelper.Filter(context.ActionArguments[p.Name].ToString()); } else if (p.ParameterType.IsClass)//当参数等于类 { ModelFieldFilter(p.Name, p.ParameterType, context.ActionArguments[p.Name]); } } } } /// <summary> /// 遍历修改类的字符串属性 /// </summary> /// <param name="key">类名</param> /// <param name="t">数据类型</param> /// <param name="obj">对象</param> /// <returns></returns> private object ModelFieldFilter(string key, Type t, object obj) { if (obj != null) { //获取类的属性集合 var pps = t.GetProperties(); foreach (var pp in pps) { if (pp.GetValue(obj) != null) { //当属性等于字符串 if (pp.PropertyType.Equals(typeof(string))) { string value = pp.GetValue(obj).ToString(); pp.SetValue(obj, XSSHelper.Filter(value)); } else if (pp.PropertyType.IsClass)//当属性等于类进行递归 { if (pp.PropertyType.IsGenericType) { var temp = pp.PropertyType.GetGenericArguments()[0]; if (temp.IsClass) { var value = pp.GetValue(obj) as dynamic; foreach (var item in value) { ModelFieldFilter(pp.Name, temp, item); } } } else if (pp.PropertyType.IsArray) { var temp = pp.PropertyType; if (temp == typeof(string[])) { var value = pp.GetValue(obj) as dynamic; var arr = new List<string>(); foreach (var item in value) { arr.Add(XSSHelper.Filter(item)); } pp.SetValue(obj, arr.ToArray()); } } else { pp.SetValue(obj, ModelFieldFilter(pp.Name, pp.PropertyType, pp.GetValue(obj))); } } } } } return obj; } }