SLaks.Blog

Making the world a better place, one line of code at a time

Don’t call Html.Encode in Razor Pages

Posted on Friday, January 21, 2011, at 1:35:00 AM UTC

One of the unique features of ASP.Net WebPages (formerly Razor) is automatic HTML encoding.  All strings printed by embedded code nuggets (@ blocks) are automatically HTML-encoded.

In addition to this feature, Razor also includes the Html.Encode method, probably copied from ASP.Net MVC.  Calling this method naively leads to a nasty surprise – the string will be double-encoded!
To see why, look more closely at a typical call: @Html.Encode("<text>").  This Razor markup will call Html.Encode, which returns the string "&lt;text&gt;".   Since it returns a string and not an IHtmlString, the Razor engine will encode it again, and render &amp;lt;text&amp;gt;.

Careful thought indicates that this behavior is probably correct.  The programmer (hopefully) knows that Razor will escape its output, so the call to Html.Encode should be an attempt to display encoded text.  In fact, this is the simplest way to display HTML-encoded text in a Razor view. 

However, even if it is correct, the behavior is unexpected and should not be relied upon.  The unambiguous way to display encoded text is to call Html.Raw:

@Html.Raw(Html.Encode(Html.Encode("Double-encoded <html> text!")))

Although it is long and clunky, this clearly shows that the text will be double-encoded.

Exercise for the reader: Why is it also necessary to call Html.Raw?

Categories: Razor, ASP.Net WebPages, ASP.Net, .Net Tweet this post

comments powered by Disqus