白名单法:
代码语言:javascript复制 public static string XssWhiteListFilter(string html)
{
html = HttpUtility.HtmlEncode(html);
//p 相关
string pattern1 = @"<p>|"
"</p>|"
@"<p style="([sS](?!<))*">";
//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="([sS](?!<))*">"
"|</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:
代码语言:javascript复制 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;
}
}
}
}