[c#] Escape text for HTML

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

sample="<span>blah<span>"

and have

<span>blah<span>

show up as plain text instead of blah only with the tags part of the html :(. Using C# not ASP

This question is related to c# html escaping

The answer is


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.


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&apos; 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>

.NET 4.0 and above:

using System.Web.Security.AntiXss;
//...
var encoded = AntiXssEncoder.HtmlEncode("input", useNamedEntities: true);

using System.Web;

var encoded = HttpUtility.HtmlEncode(unencoded);

You can use actual html tags <xmp> and </xmp> to output the string as is to show all of the tags in between the xmp tags.

Or you can also use on the server Server.UrlEncode or HttpUtility.HtmlEncode.


For those in the future looking for a simple way to do this in Razor pages, use the following:

In .cshtml:

@Html.Raw(Html.Encode("<span>blah<span>"))

In .cshtml.cs:

string rawHtml = Html.Raw(Html.Encode("<span>blah<span>"));

nobody has mentioned yet, in ASP.NET 4.0 there's new syntax to do this. instead of

<%= HttpUtility.HtmlEncode(unencoded) %>

you can simply do

<%: unencoded %>

read more here: http://weblogs.asp.net/scottgu/archive/2010/04/06/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2.aspx


If you're using .NET 4 or above and you don't want to reference System.Web, you can use WebUtility.HtmlEncode from System

var encoded = WebUtility.HtmlEncode(unencoded);

This has the same effect as HttpUtility.HtmlEncode and should be preferred over System.Security.SecurityElement.Escape.


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("“", "\""));
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to escaping

Uses for the '&quot;' entity in HTML Javascript - How to show escape characters in a string? How to print a single backslash? How to escape special characters of a string with single backslashes Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence Properly escape a double quote in CSV How to Git stash pop specific stash in 1.8.3? In Java, should I escape a single quotation mark (') in String (double quoted)? How do I escape a single quote ( ' ) in JavaScript? Which characters need to be escaped when using Bash?