开发者

Gracefully handling HTML tags on form submission in asp.net MVC 2

H开发者_运维技巧i I have a MVC site and will have users inputting text to be displayed on a web page. I am trying to come up with a graceful way of handling any HTML that the user try's to input - as you will probably be aware MVC 2 throws an error for any HTML in the text.

I use ViewModels and decorate my properties with filters from the DataAnotation class to validate my forms.

Anybody now of such a way?

Is there some crazy regex that will NOT match HTML but anything else or some other way?

I am open to any suggestions.

Thanks,

Simon


Adding the following attribute will stop the runtime from complaining:

[ValidateInput(false)]
public ActionResult SomeEvilAction ()
{
    /* ... */
}

Now it's your task to HTML encode every input you display back on a page:

<%= HttpUtility.HtmlEncode (Model.Text) %>

or

<%: Model.Text %>


I did this exact thing on a site I did the other day.

I am using a WYSIWYG editor that puts in proper html, not bb code.

I disabled validation on the page from the page directive to stop mvc throwing the potentially unsafe code exception and removed all instance of scripts tags using regex.

See Developer Art's post

You may need to add this to your web.config

<httpRuntime requestValidationMode="2.0" />

The regex I used is as follows:

(?<startTag><\s*script[^>]*>)(?<scriptContent>[\s\S]*?)(?<endTag><\s*/script>)

This will give you 3 named groups. startTag scriptContent endTag

So you can do a replace on the script element and show the content of the script, or remove it altogether.

Anything you wish to do really.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜