XSSFilterAttribute.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using Microsoft.AspNetCore.Mvc.Filters;
  2. using System;
  3. using System.Text.RegularExpressions;
  4. namespace WMS.BZWeb.Extensions
  5. {
  6. /// <summary>
  7. /// XSS 过滤器
  8. /// </summary>
  9. public class XSSFilterAttribute : ActionFilterAttribute
  10. {
  11. /// <summary>
  12. /// OnActionExecuting
  13. /// </summary>
  14. /// <param name="context"></param>
  15. public override void OnActionExecuting(ActionExecutingContext context)
  16. {
  17. //获取参数集合
  18. var ps = context.ActionDescriptor.Parameters;
  19. //遍历参数集合
  20. foreach (var p in ps)
  21. {
  22. if (context.ActionArguments.ContainsKey(p.Name))
  23. {
  24. //当参数是str
  25. if (p.ParameterType.Equals(typeof(string)))
  26. {
  27. if (context.ActionArguments[p.Name] != null)
  28. {
  29. context.ActionArguments[p.Name] = XSSHelper.XssFilter(context.ActionArguments[p.Name].ToString());
  30. }
  31. }
  32. else if (p.ParameterType.IsClass)//当参数是一个实体
  33. {
  34. PostModelFieldFilter(p.ParameterType, context.ActionArguments[p.Name]);
  35. }
  36. }
  37. }
  38. }
  39. /// <summary>
  40. /// 遍历实体的字符串属性
  41. /// </summary>
  42. /// <param name="type">数据类型</param>
  43. /// <param name="obj">对象</param>
  44. /// <returns></returns>
  45. private object PostModelFieldFilter(Type type, object obj)
  46. {
  47. if (obj != null)
  48. {
  49. foreach (var item in type.GetProperties())
  50. {
  51. if (item.GetValue(obj) != null)
  52. {
  53. //当参数是str
  54. if (item.PropertyType.Equals(typeof(string)))
  55. {
  56. string value = item.GetValue(obj).ToString();
  57. item.SetValue(obj, XSSHelper.XssFilter(value));
  58. }
  59. else if (item.PropertyType.IsClass)//当参数是一个实体
  60. {
  61. item.SetValue(obj, PostModelFieldFilter(item.PropertyType, item.GetValue(obj)));
  62. }
  63. }
  64. }
  65. }
  66. return obj;
  67. }
  68. }
  69. /// <summary>
  70. /// 过滤HTML标记
  71. /// </summary>
  72. public static class XSSHelper
  73. {
  74. /// <summary>
  75. /// XSS过滤
  76. /// </summary>
  77. /// <param name="html">html代码</param>
  78. /// <returns>过滤结果</returns>
  79. public static string XssFilter(string html)
  80. {
  81. string str = HtmlFilter(html);
  82. return str;
  83. }
  84. /// <summary>
  85. /// 过滤HTML标记
  86. /// </summary>
  87. /// <param name="Htmlstring"></param>
  88. /// <returns></returns>
  89. public static string HtmlFilter(string Htmlstring)
  90. {
  91. // 写自己的处理逻辑即可,下面给出一个比较暴力的孤哦旅,把 匹配到<[^>]*>全部过滤掉,建议慎用
  92. string result = Regex.Replace(Htmlstring, @"<[^>]*>", String.Empty);
  93. return result;
  94. }
  95. }
  96. }