3

Is there some magic existing code in MVC 2 to Html.Encode() strings and allow certain html markup, like paragraph marks and breaks? (coming from a Linq to SQL database field)

A horrible code example to achieve the effect:

Html.Encode(Model.fieldName).Replace("&lt;br /&gt;", "<br />")

What would be really nice is to overload something and pass to it an array (or object) full of allowed html tags.

3 Answers 3

5

It's not a good idea to create your own whitelist based on regular expressions because you'll likely inadvertently open a security hole for XSS.

From Sanderson's book "Pro ASP.NET MVC3 Framework": "...The only viable mitigation is strict, whitelist-based filtering: use a library like the HTML Agility Pack to ensure the user-supplied markup contains only the tags that you explicitly allow."

Sanderson goes on to supply a link to a site that demonstrates a broad range of XSS techniques that you'd have to test for if you use the regex approach. Check out http://ha.ckers.org/xss.html

Sign up to request clarification or add additional context in comments.

Comments

4

There is nothing built in to ASP.NET or MVC for this, but it's not that hard to write your own whitelist-based one with regular expressions and so on. Here's one that Jeff wrote, though it's pretty rough around the edges...

Comments

2

I can't think of anything off the bat but I guess you could write an extension method that allows you to add a paremeter/list of items to allow.

Html.Encode(Mode.fieldName, List<items> Myitems);

It could modify the allowable tags into &lt; etc and then encodes the rest like normal.

1 Comment

The only problem with going like this is that if someone explicitly puts &lt;br/&gt; in their HTML (expecting it to display like that, rather than being converted to an actual new-line) will be surprised when it gets "unescaped" by your routine...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.