Wednesday, September 1, 2010

Asp.Net 4.0 : The new <%: %> syntax

Asp.Net 4.0 introduces new code expression syntax (<%: %>) that renders output same like <%= %> but automatically encodes contents before rendering.


For example:

Let’s say we have "myContent" variable to be displayed on the web page.
For that we can write <%= Server.HtmlEncode(myContent) %>.
This works fine but developer often forgot to write Server.HtmlEncode() method and opens the door for Cross-site script injection (XSS) and HTML encoding attacks.
With asp.net 4.0 we can write the same code as <%: myContent %> which looks concise :)
So we can say <%= Server.HtmlEncode(myContent) %> is same as <%: myContent %>.