Today I would like to discuss an interesting feature that is available only in ASP.NET4. It is primarily used in MVC3 applications.

ASP.NET 4.0 comes with a Encoded Expressions <%: expression %> that will automatically convert string into html encoded. Now we can replace all occurrences of <%= %> with <%: %>.

SO what is the difference between these two? Are they same?

No they are not. The main difference is when you use the new syntax our code get encoded. Any html script in side do not gets executed by the browser.


It is just treated as content. In the previous versions you might be using Server.HtmlEncode(<%=expression %>).

So this new syntax does exactly same function as this method. We can use HtmlString type to indicate encoding is unnecessary.

Proof of Concept

I have created a Test method that returns string and that string has some HTML characters like < > to be encoded


public static string Test()
{  
    return "alert('Hello World!!! returns javascript');  HTML Encoded expression";
}

Now add 2 aspx pages. In the first page add this code.

<DIV>
<form id="form1" runat="server">
    <strong><%: Test()%></strong>
</form>
</div>
</DIV>

Now In the Second aspx page use this syntax

<DIV>
<form id="form1" runat="server">
    <strong><%= Test()%></strong>
</form>
</div>
</DIV>

Run this pages on the browser one after the other. Now if you observe, first page gives a just text where as 2nd page is not encoded it returns the script alert message along with text . And look at the viewsource you can see the difference exactly.


Advantages

-    General security threats for ASP.Net Web applications are Cross-site script injection attacks and HTML encoding attacks. This feature is nice handy way to eliminate javascript injection in your web applications.

-    Now it is easy to replace <%=exp %> to <%:exp%> and make your code or data more secured.

-    Now We do not need to specify Validate-Request to validate HTML Scripts in ASP.NET, which you may be doing it in web.config or pagelevel

Is it not so interesting?. So start playing with the feature.

Hope this helps. Let me know if any questions are clarifications.