Ask your question here : ASP.NET or MVC | C# | Windows Phone
Microsoft Technology Journals by Abhimanyu K Vatsa
HOME ABOUT RAZOR BOOK ASP.NET JQUERY C# VIDEOS MVC EBOOK ARCHIVE

22 Dec 2012

HTML Encoding in MVC

One of the best feature in Razor view engine that I like most is ‘HTML Encoding’. In many cases (like a comment form on blog) we receive the data from users and he may be trying to victimize us by sending some malicious scripts causes cross-site script injection attacks (aka XSS attack).

In ASP.NET Web Forms we have couple of ways to HTML encoding:

ASP.NET 3.5 and below: <%= Html.Encode(data to encode) %>
ASP.NET 4: <%: data to encode %>

Above approaches helps us in mitigating Cross Site Scripting (XSS) attacks in ASP.NET Web Forms.

ASP.NET MVC Razor expressions are automatically HTML encoded. It is always a good practice to validate data receiving from user before storing it in database because database can accept any malicious data specially XSS data happily but if you are using Razor to display those data on web page, you are still safe and you don’t need any special care.

Let’s look at the following image:


In the above image, you can see we have a peace of data which is not encoded. But I’m a proud Razor programmer because it handles HTML encoding automatically, here it is.


However, sometimes we need to display the HTML markup as it is on the web page, then use Html.Raw.


Note: Sometimes we need to display user input within JavaScript then we use @Ajax.JavaScriptStringEncode to encode the input. For example:

<script type="text/javascript">
$(function () {
var message = 'Message is : @Ajax.JavaScriptStringEncode(ViewBag.Message)';
$("#divmsg").html(message);
});
</script>

Hope this helps. Thanks.

Comment using Google Services (2 comments):