Html Encoded Code Expressions in ASP.NET 4

Just returned home from the Orlando Code Camp with my 3 children who were real troopers for joining me on the trip. We woke up at 4:30am for a 2+ hour drive so I could speak about What’s New in ASP.NET 4 at 8:30am.

I realized on my ride home that I neglected to mention Html Encoded Code Expressions as a new feature in ASP.NET 4. It was in my code and listed in the tutorials, but somehow in the excitement of mentioning the other ASP.NET 4 Features it got overlooked. Hence, I thought I would follow-up with a quick blog post to remedy the situation.

Html Encoded Code Expressions is a handy way to eliminate javascript injection in your web applications. So often developers forget that input from various 3rd party sources, like user input and the database, is evil and should never be trusted. Any data displayed on a browser, for example, should be properly encoded to assure it doesn’t run malicious scripts.

When you display data to a browser you will sometimes use the following code expression:


<%= data %>


If the data were somehow injected with javascript in addition to its value, such as “<script>alert(‘Hello’);</script>javascript injected”, you will get a very unwelcome javascript dialog box displaying hello in addition to the text being displayed on the screen.

If instead you were to use the new HTML Encoded Code Expression in ASP.NET 4, which replaces “=” with “:” as such:


<%: data %>


The result would be a properly encoded string which would cause the script to not be run, but instead displayed as text on the browser: “<script>alert(‘Hello’);</script>javascript injected”.


You can try the difference yourself. Put the following two statements in the source of your ASP.NET 4 Page and watch <%= … %> execute the javascript while the other, <%: … %>, encodes the javascript as text:


<%= “<script>alert(‘Hello’);</script>javascript injected” %>
<%: “<script>alert(‘Hello’);</script>javascript injected” %>


If you attended the Sarasota Web Developer Group, we went over this new ASP.NET 4 Feature in detail.


Hope this helps.


David Hayden

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>