Razor does a great job of encoding content by default. This is a good thing. It means that you’re automatically protected from things like SQL injections and XSS vulnerabilities. Let’s say you have a todo-list application, where users can enter a task name. If someone writes a task name like
But what if you wanted to output the raw, non-encoded version of the content? For example, what if you want to allow users to write arbitrary HTML (which is dangerous) — say, for a CMS or blog application? This is precisely the situation I ran into with Planetary CMS.
The solution? Quite simple, really: instead of using
@ to display content, use
But wait! ASP.NET serves up this amazing error message:
A potentially dangerous Request.Form value was detected from the client [...]
So there are two layers of security: one is that content is encoded by default, and the second is that potentially dangerous content will not be displayed (unless you explicitly give it permission to do so).
So how do you tell ASP.NET MVC3 that this is okay? Simply annotate your controller’s actions (in my case, it was only on the
HttpPost version of the
Create method) with
ValidateInput(false). And everything will display as expected.
And of course, be careful when you’re doing this. Understand the security that you’ve unwound, and the potential implications of it. If you really need to do this, move forward, and be cognizant of what you are getting into.