123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- using Microsoft.AspNetCore.Mvc.Filters;
- using System;
- using System.Text.RegularExpressions;
- namespace WMS.BZWeb.Extensions
- {
- /// <summary>
- /// XSS 过滤器
- /// </summary>
- public class XSSFilterAttribute : ActionFilterAttribute
- {
- /// <summary>
- /// OnActionExecuting
- /// </summary>
- /// <param name="context"></param>
- 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]);
- }
- }
- }
- }
- /// <summary>
- /// 遍历实体的字符串属性
- /// </summary>
- /// <param name="type">数据类型</param>
- /// <param name="obj">对象</param>
- /// <returns></returns>
- 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;
- }
- }
- /// <summary>
- /// 过滤HTML标记
- /// </summary>
- public static class XSSHelper
- {
- /// <summary>
- /// XSS过滤
- /// </summary>
- /// <param name="html">html代码</param>
- /// <returns>过滤结果</returns>
- public static string XssFilter(string html)
- {
- string str = HtmlFilter(html);
- return str;
- }
- /// <summary>
- /// 过滤HTML标记
- /// </summary>
- /// <param name="Htmlstring"></param>
- /// <returns></returns>
- public static string HtmlFilter(string Htmlstring)
- {
- // 写自己的处理逻辑即可,下面给出一个比较暴力的孤哦旅,把 匹配到<[^>]*>全部过滤掉,建议慎用
- string result = Regex.Replace(Htmlstring, @"<[^>]*>", String.Empty);
- return result;
- }
- }
- }
|