3

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.

Jonathan
  • 227
  • 3
  • 9

3 Answers3

3

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.

fan711
  • 716
  • 3
  • 13
2

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 
}
Nicolas
  • 21
  • 1
  • Could you please edit your answer and add an explanation why the answer by @fan711 is depricated? – honk Nov 20 '14 at 19:46
1

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

Community
  • 1
  • 1
gideon
  • 19,329
  • 11
  • 72
  • 113
  • Thanks, I forgot to say that I dont want to turn off validation for the entire action. That seems a little bit drastic just to handle HTML input. I have other validation that I want to have happen. – Jonathan Mar 18 '11 at 17:39