Escape text for HTML

后端 未结 9 802
别那么骄傲
别那么骄傲 2020-11-28 04:50

How do i escape text for html use in C#? I want to do

sample=\"blah\"

and have

blah&l         


        
相关标签:
9条回答
  • 2020-11-28 05:35

    Also, you can use this if you don't want to use the System.Web assembly:

    var encoded = System.Security.SecurityElement.Escape(unencoded)
    

    Per this article, the difference between System.Security.SecurityElement.Escape() and System.Web.HttpUtility.HtmlEncode() is that the former also encodes apostrophe (') characters.

    0 讨论(0)
  • 2020-11-28 05:37

    Didn't see this here

    System.Web.HttpUtility.JavaScriptStringEncode("Hello, this is Satan's Site")
    

    it was the only thing that worked (asp 4.0+) when dealing with html like this. The' gets rendered as ' (using htmldecode) in the html, causing it to fail:

    <a href="article.aspx?id=268" onclick="tabs.open('modules/xxx/id/268', 'It&apos;s Allstars'); return false;">It's Allstars</a>
    
    0 讨论(0)
  • 2020-11-28 05:37

    there are some special quotes characters which are not removed by HtmlEncode and will not be displayed in Edge or IE correctly like ” and “ . you can extent replacing these characters with something like below function.

    private string RemoveJunkChars(string input)
    {
        return HttpUtility.HtmlEncode(input.Replace("”", "\"").Replace("“", "\""));
    }
    
    0 讨论(0)
提交回复
热议问题