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'
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'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("“", "\""));
}
Source: Stackoverflow.com