【问题标题】:Escape C# string to HTML [duplicate]将 C# 字符串转义为 HTML [重复]
【发布时间】:2012-02-01 00:51:25
【问题描述】:

我有一个带有特殊字符的字符串,如下所示:

äöüß&

现在我想把它放在一个 HTML 文档中,并且需要转义这些字符。有没有一种优雅的方式来做到这一点?

我可以这样做:

string html;
html = html.Replace("ü", "uu¨");
html = html.Replace("ß", "ß");
....

但我不想对所有可能的特殊字符都这样做。

【问题讨论】:

    标签: c# html escaping


    【解决方案1】:

    让框架为您完成工作。

    你可以试试HtmlEncode:

    string encodedHtml = Server.HtmlEncode(html);
    

    【讨论】:

    • @juergend - 检查我链接到的文档。具有命名空间和程序集(以防您需要添加引用)。
    • 一开始我没有看到。实际上,即使在我的项目中使用System.Web 命名空间并引用 System.Web.dll 之后,VS2010 仍然找不到 Server 类。但它发现这非常有效:HttpUtility.HtmlEncode
    【解决方案2】:

    我建议养成使用Microsoft's AntiXSS Library的习惯,然后打电话

    AntiXSS.HtmlEncode(yourstring);
    

    如果您需要将其包含在正文中,或者

    AntiXSS.HtmlAttributeEncode(yourstring);
    

    如果它在 HTML 属性中。

    【讨论】:

    • 这个库已经过时,被 Encoder.HtmlEncode() 取代。
    【解决方案3】:

    还有这个,适用于 XML,但它应该可以与 HTML 一起工作:

    System.Security.SecurityElement.Escape( string s );

    【讨论】:

    猜你喜欢
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 2012-09-03
    • 2020-08-27
    • 2015-09-27
    • 1970-01-01
    相关资源
    最近更新 更多