How Does <%: ... %> Differ From <%= ... %> in ASP.Net MVC


The <%= ... %> syntax has been available in ASP.NET since the platform was first invented. Just like the equivalent syntaxes in PHP, JSP, Classic ASP, and many other platforms, it’s a way to emit dynamic values into the HTML response. But this raises a question of security: if the dynamic value may originally have been supplied by a user, how can you be sure it doesn’t contain any unwanted HTML or malicious JavaScript? The standard way to avoid any such risk is to HTML-encode the value before emitting it, which converts any special characters (e.g., <) to harmless HTML entities (e.g., &lt;) that the browser knows to treat as plain text. <%= Html.Encode(ViewData["greeting"]) %> The tricky bit is remembering to write Html.Encode() all the time, especially considering that sometimes you must not encode certain values because they may contain HTML that you do want (e.g., from HTML helper methods like Html.ActionLink(), which already take care of encoding any parameter values for you), and you can’t HTML-encode a single value twice. If you forget to use Html.Encode() on a usersupplied value, you put your entire application at risk of cross-site scripting (XSS) attacks, as detailed in Chapter 15.

To solve this difficulty, in .NET 4 Microsoft enhanced the ASP.NET page compiler (which ASP.NET MVC uses by default for its views) to support a new syntax, <%: ... %>, intended to replace <%= ... %>. The difference is that <%: ... %> automatically HTML-encodes its output, blocking the XSS risk, except when the value being rendered comes from a HTML helper, in which case it knows not to reencode the value because it’s already safe. This is a huge simplification for developers: now, all you have to do is always use <%: ... %>, and preferably have some kind of hypnosis or brain surgery to erase all memory of the older, dangerous <%= ... %> syntax.

Comments

Popular posts from this blog

Hosting WCF in IIS(9 Steps)

Difference between IEnumerator and IEnumerable

MVC and MVVM Architecture