C#笔记:XSS攻击防御 白名单法: public static string XssWhiteListFilter(string html) { html = HttpUtility.HtmlEncode(html); //p 相关 string pattern1 = @"<p>|" + "</p>|" + @"<p style="([\s\S](?!<))*">"; //img string pattern2 = @"<img src="http://www.yinzihao.com.cn/.*"/>"+ "|<img src="http://img.baidu.com/(.(?!<))*"/>"; //a string pattern3 = "<a href="http://www.yinzihao.com.cn/(.(?!<))*">(.(?!<))*</a>"; //br strong string pattern4 = "<br/>|<strong>|</strong>"; //span string pattern5 = @"<span style="([\s\S](?!<))*">" + "|</span>"; List<string> lstPattern = new List<string>() { pattern1, pattern2, pattern3, pattern4, pattern5 }; foreach (string pat in lstPattern) { Regex reg = new Regex(pat, RegexOptions.IgnoreCase); MatchCollection mc = reg.Matches(html); foreach (Match item in mc) { html = html.Replace(item.Value, HttpUtility.HtmlDecode(item.Value)); } } return html; }filter: public class XssFilter:ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var parameters = filterContext.ActionDescriptor.GetParameters(); foreach (var parameter in parameters) { if (parameter.ParameterType == typeof(string)) { //获取字符串参数原值 var orginalValue = filterContext.ActionParameters[parameter.ParameterName] as string; //使用过滤算法处理字符串 var filteredValue = MvcDatu.Controllers.Helper.XssWhiteListFilter(orginalValue); //将处理后值赋给参数 filterContext.ActionParameters[parameter.ParameterName] = filteredValue; } } } } 来自 大脸猫 写于 2015-02-06 20:27 -- 更新于2020-10-19 13:06 -- 0 条评论