c# - 如何在 ASP.NET 中清理来自 MCE 的输入?

标签 c# asp.net tinymce xss

C# 中是否有实用程序/函数来清理 tinyMCE 富文本的源代码。我想删除危险标签,但想将安全 html 标签列入白名单。

最佳答案

我认为没有内置的 C# 清理程序可供您使用,但这是我在遇到同样问题时所做的。我使用了 AjaxControlToolkit 附带的 HtmlAgilityPackSanitizerProvider。代码如下所示:

private static AjaxControlToolkit.Sanitizer.HtmlAgilityPackSanitizerProvider sanitizer = new AjaxControlToolkit.Sanitizer.HtmlAgilityPackSanitizerProvider();

private static Dictionary<string, string[]> elementWhitelist = new Dictionary<string, string[]>
{
    {"b"            , new string[] { "style" }},
    {"strong"       , new string[] { "style" }},
    {"i"            , new string[] { "style" }},
    {"em"           , new string[] { "style" }},
    {"u"            , new string[] { "style" }},
    {"strike"       , new string[] { "style" }},
    {"sub"          , new string[] { "style" }},
    {"sup"          , new string[] { "style" }},
    {"p"            , new string[] { "align" }},
    {"div"          , new string[] { "style", "align" }},
    {"ol"           , new string[] { }},
    {"li"           , new string[] { }},
    {"ul"           , new string[] { }},
    {"a"            , new string[] { "href" }},
    {"font"         , new string[] { "style", "face", "size", "color" }},
    {"span"         , new string[] { "style" }},
    {"blockquote"   , new string[] { "style", "dir" }},
    {"hr"           , new string[] { "size", "width", "id" }},
    {"img"          , new string[] { "src" }},
    {"h1"           , new string[] { "style" }},
    {"h2"           , new string[] { "style" }},
    {"h3"           , new string[] { "style" }},
    {"h4"           , new string[] { "style" }},
    {"h5"           , new string[] { "style" }},
    {"h6"           , new string[] { "style" }}
};

private static Dictionary<string, string[]> attributeWhitelist = new Dictionary<string, string[]>
{
    {"style"    , new string[] {}},
    {"align"    , new string[] {}},
    {"href"     , new string[] {}},
    {"face"     , new string[] {}},
    {"size"     , new string[] {}},
    {"color"    , new string[] {}},
    {"dir"      , new string[] {}},
    {"width"    , new string[] {}},
    {"id"       , new string[] {}},
    {"src"      , new string[] {}}
};

public string SanitizeHtmlInput(string unsafeStr)
{
    return sanitizer.GetSafeHtmlFragment(unsafeStr, elementWhitelist, attributeWhitelist);
}

希望这对您有所帮助。

关于c# - 如何在 ASP.NET 中清理来自 MCE 的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17581936/

相关文章:

c# - 如何使用正则表达式从字符串(如果有)中删除最后一个逗号和空格?

c# - 即使抛出异常,HttpContext.Current 是否也被释放?

c# - 打印文档:适合页面

c# - 多维关联数组 C#

javascript - 在 TinyMCE 中追加属性值

javascript - 触发TinyMce文件上传

c# - DateTime.AddMilliSeconds 似乎不起作用

asp.net - 样式规则中的选择器后缺少左大括号 '({)'

asp.net - 从 C#.net 中的 SVN 存储库下载文件

javascript - IE8 上的 TinyMCE : text cursor problem