【问题标题】:Sanitizing HTML using Jeff Atwood's example使用 Jeff Atwood 的示例清理 HTML
【发布时间】:2010-06-28 20:59:49
【问题描述】:

我正在使用找到的 Jeff Atwood 的代码清理我的 Html here

但我遇到的问题是当我在表单中输入 Markdown 链接时(它们被删除了)

<http://www.example.com>

这是我正在使用的代码。

private static Regex _tags = new Regex("<[^>]*(>|$)",
    RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled);
private static Regex _whitelist = new Regex(@"
    ^</?(b(lockquote)?|code|d(d|t|l|el)|em|h(1|2|3)|i|kbd|li|ol|p(re)?|s(ub|up|trong|trike)?|ul)>$|
    ^<(b|h)r\s?/?>$",
    RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);
private static Regex _whitelist_a = new Regex(@"
    ^<a\s
    href=""(\#\d+|(https?|ftp)://[-a-z0-9+&@#/%?=~_|!:,.;\(\)]+)""
    (\stitle=""[^""<>]+"")?\s?>$|
    ^</a>$",
    RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);
private static Regex _whitelist_img = new Regex(@"
    ^<img\s
    src=""https?://[-a-z0-9+&@#/%?=~_|!:,.;\(\)]+""
    (\swidth=""\d{1,3}"")?
    (\sheight=""\d{1,3}"")?
    (\salt=""[^""<>]*"")?
    (\stitle=""[^""<>]*"")?
    \s?/?>$",
    RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);


/// <summary>
/// sanitize any potentially dangerous tags from the provided raw HTML input using 
/// a whitelist based approach, leaving the "safe" HTML tags
/// CODESNIPPET:4100A61A-1711-4366-B0B0-144D1179A937
/// </summary>
public static string Sanitize(string html)
{
    if (String.IsNullOrEmpty(html)) return html;

    string tagname;
    Match tag;

    // match every HTML tag in the input
    MatchCollection tags = _tags.Matches(html);
    for (int i = tags.Count - 1; i > -1; i--)
    {
        tag = tags[i];
        tagname = tag.Value.ToLowerInvariant();

        if(!(_whitelist.IsMatch(tagname) || _whitelist_a.IsMatch(tagname) || _whitelist_img.IsMatch(tagname)))
        {
            html = html.Remove(tag.Index, tag.Length);
            System.Diagnostics.Debug.WriteLine("tag sanitized: " + tagname);
        }
    }

    return html;
}

【问题讨论】:

  • jeff atwood 的 html 清理代码无法从 refactormycode.com/codes/333-sanitize-html 获得。它现在显示离线。您能否提供 jeff 的 html 清理代码。我的项目非常需要它。
  • 抱歉,我强烈建议不要使用重构我的代码。他们的数据库被入侵了,我在我的自定义 rfmc@mydomain 电子邮件地址中被垃圾邮件遗忘了。至于图书馆,这是很久以前的事了,我现在不知道在哪里可以找到它。
  • 您可以通过Web Archive查看该网站。

标签: markdown sanitize


【解决方案1】:

是的,因为那不是有效的 HTML...所以代码正在做它声称要做的事情。

由于 Markdown 允许嵌入 HTML,但 HTML 不允许(所有形式的)嵌入 Markdown,我建议您先将 Markdown 转换为 HTML,然后然后对其进行清理...

【讨论】:

  • 这很容易。当解决方案如此简单时,我喜欢它……甚至没有从这些方面考虑过。 uwao.About = Trim(Utilities.HtmlSanitizer.Sanitize(MarkDownSharp.Transform(user.About)))
猜你喜欢
  • 2013-06-04
  • 2012-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-09
相关资源
最近更新 更多