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
using System.Web;
var encoded = HttpUtility.HtmlEncode(unencoded);
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.
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
.
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:
New <%: %> Syntax for HTML Encoding Output in ASP.NET 4 (and ASP.NET MVC 2)
.NET 4.0 and above:
using System.Web.Security.AntiXss;
//...
var encoded = AntiXssEncoder.HtmlEncode("input", useNamedEntities: true);
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
.
` instead
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>"));
You can use:
System.Web.HttpUtility.JavaScriptStringEncode("Hello, this is Satan's Site")
It was the only thing that worked (ASP.NET 4.0+) when dealing with HTML like this. The'
gets rendered as '
(using htmldecode) in the HTML content, causing it to fail:
<a href="article.aspx?id=268" onclick="tabs.open('modules/xxx/id/268', 'It's Allstars'); return false;">It's Allstars</a>
There are some special quotes characters which are not removed by HtmlEncode and will not be displayed in Edge or Internet Explorer correctly, like ”
and “
. You can extend replacing these characters with something like the below function.
private string RemoveJunkChars(string input)
{
return HttpUtility.HtmlEncode(input.Replace("”", "\"").Replace("“", "\""));
}