XSSHelper.cs 1.58 KB
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Hh.Mes.Common.XSS
{
    /// <summary>
    /// 在新增和编辑上面添加特性[XSS] xss漏洞解决
    /// IIS如何“设置HTTP请求头(X-Frame-Options)” https://jingyan.baidu.com/article/f0e83a25e7fc6f62e59101ef.html
    /// </summary>
    public class XSSHelper
    {
        /// <summary>
        /// XSS过滤
        /// </summary>
        /// <param name="html">html代码</param>
        /// <returns>过滤结果</returns>
        public  string XssFilter(string html)
        {
            string str = HtmlFilter(html);
            return str;
        }

        /// <summary>
        /// 过滤HTML标记
        /// </summary>
        /// <param name="Htmlstring"></param>
        /// <returns></returns>
        public  string HtmlFilter(string Htmlstring)
        {
            // 写自己的处理逻辑即可,
            if (string.IsNullOrEmpty(Htmlstring)) return string.Empty;
            string ihtml = Htmlstring.Replace("<script", "&lt;script");
            ihtml = ihtml.Replace("script>", "script&gt;");
            ihtml = ihtml.Replace("<%", "&lt;%");
            ihtml = ihtml.Replace("<", "&lt");
            
            ihtml = ihtml.Replace("%>", "%&gt;");
            ihtml = ihtml.Replace("<$", "&lt;$");
            ihtml = ihtml.Replace("$>", "$&gt;");

            //过滤SQL非法字符并格式化html代码
            ihtml = ihtml.Replace("'", "");
            ihtml = ihtml.Replace("--", "——");
            return ihtml;

        }
    }
}