How to avoid HttpRequestValidationException in ASP.NET MVC rendering the same view which caused the exception


Question

I just want to know how to validate (or clean) user input in ASP.NET MVC so that an HttpRequestValidationException will not be thrown regardless of the values submitted. For example, with a text input, if the user inputs <BR/>, it will cause an exception and the Yellow Screen of Death will be shown. I don't want that. I want to catch the exception and to make visible an user friendly error in the current view, preferably with the controls loaded with the same values submitted.

I have found this http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html, but it is useless for my purpose. Also, I have found this http://msdn.microsoft.com/en-us/library/aa973813.aspx and tried to put inside a model binder but I couldn't make to work.

1
36
11/1/2008 10:10:54 PM

Accepted Answer

With the latest version of ASP.NET MVC (the RC, at the time of writing this) you can just put an attribute on either your controller class or your action method, e.g.:

[ValidateInput(false)]
public ActionResult create()
{
    // ...method body
}

The ValidateInputAttribute is in System.Web.Mvc.

But as others have said, you do then have to perform your own manual input validation or cleaning.

Using MVC 3, you must also ensure this is in your Web.config: <system.web><httpRuntime requestValidationMode="2.0" /></system.web>

40
9/23/2011 10:00:29 PM

In ASP MVC 3 you can use the [AllowHtml] attribute on individual fields/properties in your Model/ViewModel to turn off validation for just that field, which is pretty nice. I will add this attribute to certain fields in my model, and then use the excellent AntiXSS library (also available via NuGet) to sanitize the user input by calling the Sanitizer.GetSafeHtmlFragment(mymodel.Description) (where the "Description" property is a string property on my view model, that has the [AllowHtml] attribute applied)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon