Every time a user posts something containing <
or >
in a page in my web application, I get this exception thrown.
I don't want to go into the discussion about the smartness of throwing an exception or crashing an entire web application because somebody entered a character in a text box, but I am looking for an elegant way to handle this.
Trapping the exception and showing
An error has occurred please go back and re-type your entire form again, but this time please do not use <
doesn't seem professional enough to me.
Disabling post validation (validateRequest="false"
) will definitely avoid this error, but it will leave the page vulnerable to a number of attacks.
Ideally: When a post back occurs containing HTML restricted characters, that posted value in the Form collection will be automatically HTML encoded.
So the .Text
property of my text-box will be something & lt; html & gt;
Is there a way I can do this from a handler?
In the web.config file, within the tags, insert the httpRuntime element with the attribute requestValidationMode="2.0". Also add the validateRequest="false" attribute in the pages element.
Example:
Another solution is:
You can catch that error in Global.asax. I still want to validate, but show an appropriate message. On the blog listed below, a sample like this was available.
Redirecting to another page also seems like a reasonable response to the exception.
http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html
For MVC, ignore input validation by adding
above each Action in the Controller.
None of the suggestions worked for me. I did not want to turn off this feature for the whole website anyhow because 99% time I do not want my users placing HTML on web forms. I just created my own work around method since I'm the only one using this particular application. I convert the input to HTML in the code behind and insert it into my database.
I was getting this error too.
In my case, a user entered an accented character
á
in a Role Name (regarding the ASP.NET membership provider).I pass the role name to a method to grant Users to that role and the
$.ajax
post request was failing miserably...I did this to solve the problem:
Instead of
Do this
@Html.Raw
did the trick.I was getting the Role name as HTML value
roleName="Cadastro bás"
. This value with HTML entityá
was being blocked by ASP.NET MVC. Now I get theroleName
parameter value the way it should be:roleName="Cadastro Básico"
and ASP.NET MVC engine won't block the request anymore.