防XSS攻击过滤器

/// <summary>
    /// 防XSS攻击
    /// date:2020-07-28
    /// </summary>
    public class XssFilter : ActionFilterAttribute
    {
        private const string strRegex = @"<[^>]+?style=[\w]+?:expression\(|\b(alert|confirm|prompt)\b|^\+/v(8|9)|<[^>]*?=[^>]*?&#[^>]*?>|\b(and|or)\b.{1,6}?(=|>|<|\bin\b|\blike\b)|/\*.+?\*/|<\s*script\b|<\s*img\b|\bEXEC\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\s+(TABLE|DATABASE)";
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.RequestContext.HttpContext.Request;
            if (request.HttpMethod == "GET")
            {
                for (int i = 0; i < request.QueryString.Count; i++)
                {
                    var result = CheckData(request.QueryString[i].ToString());
                    if (result)
                    {
                        filterContext.Result = new JsonResult() { Data = new { ret = -1, msg = "提交的数据含有非法字符" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                        break;
                    }
                }
            }
            else
            {
                for (int i = 0; i < request.Form.Count; i++)
                {
                    var result = CheckData(request.Form[i].ToString());
                    if (result)
                    {
                        filterContext.Result = new JsonResult() { Data = new { ret = -5, msg = "提交的数据含有非法字符" } };
                        break;
                    }
                }
            }
        }

        private static bool CheckData(string inputData)
        {
            if (Regex.IsMatch(inputData, strRegex))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

xss

相关推荐