Html Encoded Code Expressions in asp.net 4.0

Html Encoded Code Expressions

Some ASP.NET sites (especially with ASP.NET MVC) rely heavily on using <%= expression %> (often called “code nuggets”) to write some text to the response. When you use code nuggets, it is easy to forget to HTML-encode the text. When the text comes from user input, it can leave pages open to an XSS (Cross Site Scripting) attack.

ASP.NET 4 introduces the following new syntax for code expressions:

<%: expression %>

This syntax uses HTML encoding by default when writing to the response. This new expression effectively translates to the following:

<%= HttpUtility.HtmlEncode(expression) %>

For example, <%: Request["UserInput"] %> would html encode the value of Request["UserInput"].

The goal of this feature is to make it possible to replace all instances of the old syntax with the new syntax so that you are not forced to decide at every step which one to use. However, there are cases in which the text being output is meant to be HTML or is already encoded, in which case this could lead to double encoding.

For those cases, ASP.NET 4 introduces a new interface, IHtmlString, along with a concrete implementation, HtmlString. Instances of these types let you indicate that the return value is already properly encoded (or otherwise examined) for displaying as HTML, and that therefore the value should not be HTML-encoded again. For example, the following should not be (and is not) HTML encoded:

<%: new HtmlString("<strong>HTML that is not encoded</strong>") %>

ASP.NET MVC 2 helper methods have been updated to work with this new syntax so that they are not double encoded, but only when you are running ASP.NET 4. This new syntax does not work when you run an application using ASP.NET 3.5 SP1.

Keep in mind that this does not guarantee protection from XSS attacks. For example, HTML that uses attribute values that are not in quotation marks can contain user input that is still susceptible. Note that the output of ASP.NET controls and ASP.NET MVC helpers always includes attribute values in quotation marks, which is the recommended approach.

Likewise, this syntax does not perform JavaScript encoding, such as when you create a JavaScript string based on user input.

Posted in: asp.net | Tags: asp.net 4.0 html html encoed code expression httputility userinput ihtmlstring