Jonathan
Jonathan

Reputation: 267

How can I ignore HttpRequestValidationException and encoded HTML myself during model binding?

I'm trying to figure out how I can ignore a HttpRequestValidationException begin thrown during model binding.

Here's the deal, I know how to handle HTML being posted and bound to a property that expects HTML (using the AllowHtml attribute) but when a user posts HTML in a field that is not supposed to allow HTML, I want to automatically encode that value during binding to the model.

I've created a custom model binder to catch the HttpRequestValidationException being thrown but whenever I try to get the value from Request.Form, the same exception gets thrown.

Is there an automatic way to do this in MVC3?

Do I need to add AllowHtml to all the properties in the model and then encode it myself in the action?

Can I get access to the HTML being posted to me during model binding without it throwing HttpRequestValidationException every time I request it from Request.Form?

Thanks for any help you can provide.

Edit I don't want to turn off validation on the entire action. That's a little bit drastic if I want to make sure that an exception isnt thrown when someone enters html in a form they shouldn't have.

Upvotes: 3

Views: 3253

Answers (3)

Nicolas
Nicolas

Reputation: 21

For me the answer by fan711 is now depricated. Now you should use

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
{ 
    //... code here 
    controllerContext.HttpContext.Request.Unvalidated.Form.GetValues(key); 
    //... code here 
}

Upvotes: 2

fan711
fan711

Reputation: 716

Same problem occured to me. Even on this older thread i'd like to share the solution. The answer is hard to find but very simple. There's an extension method which allows access of form and querystring unvalidated.

System.Web.Helpers.UnvalidatedRequestValues unvalidatedRequest = System.Web.Helpers.Validation.Unvalidated(Context.Request)
System.Collections.Specialized.NameValueCollection form = unvalidatedRequest.form

No need for requestValidationMode or turning off validation at all. This article led me to the solution.

Upvotes: 3

gideon
gideon

Reputation: 19465

Something like:

[HttpPost, ValidateInput(false)]
public ActionResult Edit(FormCollection collection)
{
    // ...
}

See this for more: A potentially dangerous Request.Form value was detected from the client

Upvotes: 1

Related Questions