New <%: %> Code Syntax in ASP.NET 4.0

Apr 7, 2010 Posted by Lara Kannan
HTML Encoding

Cross-site script injection (XSS) and HTML encoding attacks are two of the most common security issues that plague web-sites and applications. They occur when hackers find a way to inject client-side script or HTML markup into web-pages that are then viewed by other visitors to a site.

This can be used to both vandalize a site, as well as enable hackers to run client-script code that steals cookie data and/or exploits a user’s identity on a site to do bad things.

One way to help mitigate against cross-site scripting attacks is to make sure that rendered output is HTML encoded within a page. This helps ensures that any content that might have been input/modified by an end-user cannot be output back onto a page containing tags like <script> or <img> elements.

How to HTML Encode Content Today

ASP.NET applications (especially those using ASP.NET MVC) often rely on using code-nugget expressions to render output. Developers today often use the Server.HtmlEncode() or HttpUtility.Encode() helper methods within these expressions to HTML encode the output before it is rendered. This can be done using code like below:

<div class="someclass">
<%= Server.HtmlEncode(Model.Content) %>

While this works fine, there are two downsides of it:

  • It is a little verbose
  • Developers often forget to call the Server.HtmlEncode method – and there is no easy way to verify its usage across an app

New Code Nugget Syntax

With ASP.NET 4 we are introducing a new code expression syntax () that renders output like blocks do – but which also automatically HTML encodes it before doing so.

This eliminates the need to explicitly HTML encode content like we did in the example above. Instead, you can just write the more concise code below to accomplish the exact same thing:

<div class="someclass">
<%: Model.Content %>

We chose the syntax so that it would be easy to quickly replace existing instances of code blocks. It also enables you to easily search your code-base for elements to find and verify any cases where you are not using HTML encoding within your application to ensure that you have the correct behavior.

Happy Coding!!!

Thanks : Scottgu.


Post a Comment