using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Text.RegularExpressions; namespace WMS.BZWeb.Extensions { /// /// XSS 过滤器 /// public class XSSFilterAttribute : ActionFilterAttribute { /// /// OnActionExecuting /// /// public override void OnActionExecuting(ActionExecutingContext context) { //获取参数集合 var ps = context.ActionDescriptor.Parameters; //遍历参数集合 foreach (var p in ps) { if (context.ActionArguments.ContainsKey(p.Name)) { //当参数是str if (p.ParameterType.Equals(typeof(string))) { if (context.ActionArguments[p.Name] != null) { context.ActionArguments[p.Name] = XSSHelper.XssFilter(context.ActionArguments[p.Name].ToString()); } } else if (p.ParameterType.IsClass)//当参数是一个实体 { PostModelFieldFilter(p.ParameterType, context.ActionArguments[p.Name]); } } } } /// /// 遍历实体的字符串属性 /// /// 数据类型 /// 对象 /// private object PostModelFieldFilter(Type type, object obj) { if (obj != null) { foreach (var item in type.GetProperties()) { if (item.GetValue(obj) != null) { //当参数是str if (item.PropertyType.Equals(typeof(string))) { string value = item.GetValue(obj).ToString(); item.SetValue(obj, XSSHelper.XssFilter(value)); } else if (item.PropertyType.IsClass)//当参数是一个实体 { item.SetValue(obj, PostModelFieldFilter(item.PropertyType, item.GetValue(obj))); } } } } return obj; } } /// /// 过滤HTML标记 /// public static class XSSHelper { /// /// XSS过滤 /// /// html代码 /// 过滤结果 public static string XssFilter(string html) { string str = HtmlFilter(html); return str; } /// /// 过滤HTML标记 /// /// /// public static string HtmlFilter(string Htmlstring) { // 写自己的处理逻辑即可,下面给出一个比较暴力的孤哦旅,把 匹配到<[^>]*>全部过滤掉,建议慎用 string result = Regex.Replace(Htmlstring, @"<[^>]*>", String.Empty); return result; } } }