This blog post is to explain Cross-site scripting with little more detail and how ASP.NET MVC prevents it to an extent.
Simple way to avoid this attack is to encode the HTML code i.e. make that as NON HTML code for the browser. Beginning from ASP.NET MVC2 view engines encoded the string so that any html code inside the string will be made as non html code e.g. <div> will become <div> and <script> will become <script> so user doesn’t get a chance to inject their own HTML code.
Syntax for HTML encoding
1. <%: model.something %> syntax in WebForms
2. It is automatic in Razor i.e. @
model.something will auto encode automatically no
need to do anything to encode.
3. MVC3 HTML Helper methods return the encoded string automatically. e.g.
Html.Label will return the encoded string
If you don’t need to encode use the following syntax
1. <%= %> syntax on webforms
2. HTML.Raw syntax on Razor
One can also stop accepting content that contains HTML code on the server side (ASP.NET configuration to stop accepting that content) but there are requirements where we need to accept those content and display in safe manner and above would be useful for those cases.