Outputting Raw HTML in Razor

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 alert('opening!');, they will see exactly what they entered — no javascript popup. You’re safe.

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 @Html.Raw(...).

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.

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Web and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>