
通过正则表达式来过滤字符串中的JS脚本,防止用户在添加资料时插入js脚本,代码如下:
#region 过滤JS/CSS脚本 /// <summary> /// 过滤JS脚本 /// </summary> /// <param name="html">要过滤的内容</param> /// <returns></returns> public static string WipeScript(string html) { if (string.IsNullOrEmpty(html)) return html; System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex.Replace(html, ""); //过滤<script></script>标记 System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex1.Replace(html, ""); //过滤href=javascript: (<A>) 属性 System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex2.Replace(html, " _disibledevent="); //过滤其它控件的on...事件 System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex3.Replace(html, ""); //过滤iframe System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex4.Replace(html, ""); //过滤frameset System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"javascript:", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex5.Replace(html, ""); //过滤所有javascript System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@":*expression", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex6.Replace(html, ""); //过滤所有javascript System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"<!--[\s\S]*-->", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex7.Replace(html, ""); //过滤所有HTML说明标签 return html; } #endregion