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:
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() = <p>"what's up!" he said</p>
2. WebUtility.HtmlEncode() = <p>"what's up!" he said</p>
3. AntiXssEncoder.HtmlEncode() = <p>"what's up!" he said</p>