/// <summary> /// 防XSS攻击 /// date:2020-07-28 /// </summary> public class XssFilter : ActionFilterAttribute { private const string strRegex = @"<[^>]+?style=[w]+?:expression(|(alert|confirm|prompt)|^+/v(8|9)|<[^>]*?=[^>]*?&#[^>]*?>|(and|or).{1,6}?(=|>|<|in|like)|/*.+?*/|<s*script|<s*img|EXEC|UNION.+?SELECT|UPDATE.+?SET|INSERTs+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; } } }