C# - How to escape text for HTML

Characters that are part of the language of HTML must be escaped before they can be displayed in a HTML document.

E.g. < > &


HTML reserved characters that are not escaped will be interpreted by the browser as HTML, which may cause the page to display incorrectly.


The top 3 methods for escaping HTML text in C# are:

  1. HttpUtility.HtmlEncode()
  2. WebUtility.HtmlEncode()
  3. AntiXssEncoder.HtmlEncode()


  static void Main(string[] args)
  {
      var html = @"<p>""what's up!"" he said</p>";
  
      var enc1 = System.Web.HttpUtility.HtmlEncode(html);
      var enc2 = System.Net.WebUtility.HtmlEncode(html);
      var enc3 = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(html, useNamedEntities: true);
  
      Console.WriteLine("Encoding string: " + html);
  
      Console.WriteLine("");
      Console.WriteLine("{0,-30} = {1}", "1. HttpUtility.HtmlEncode()", enc1);
      Console.WriteLine("{0,-30} = {1}", "2. WebUtility.HtmlEncode()", enc2);
      Console.WriteLine("{0,-30} = {1}", "3. AntiXssEncoder.HtmlEncode()", enc3);
      Console.WriteLine("");
  }
  

Program output:


  Encoding string: <p>""what's up!"" he said</p>
  
  1. HttpUtility.HtmlEncode()    = &lt;p&gt;&quot;what&#39;s up!&quot; he said&lt;/p&gt;
  2. WebUtility.HtmlEncode()     = &lt;p&gt;&quot;what&#39;s up!&quot; he said&lt;/p&gt;
  3. AntiXssEncoder.HtmlEncode() = &lt;p&gt;&quot;what&#39;s up!&quot; he said&lt;/p&gt;
  

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath