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?
You could also use JavaScript's escape(string) function to replace the special characters. Then server side use Server.URLDecode(string) to switch it back.
This way you don't have to turn off input validation and it will be more clear to other programmers that the string may have HTML content.
There's a different solution to this error if you're using ASP.NET MVC:
C# sample:
Visual Basic sample:
If you are on .NET 4.0 make sure you add this in your web.config file inside the
<system.web>
tags:In .NET 2.0, request validation only applied to
aspx
requests. In .NET 4.0 this was expanded to include all requests. You can revert to only performing XSS validation when processing.aspx
by specifying:You can disable request validate entirely by specifying:
If you don't want to disable ValidateRequest you need to implement a JavaScript function in order to avoid the exception. It is not the best option, but it works.
Then in code behind, on the PageLoad event, add the attribute to your control with the next code:
I ended up using JavaScript before each postback to check for the characters you didn't want, such as:
Granted my page is mostly data entry, and there are very few elements that do postbacks, but at least their data is retained.
In ASP.NET, you can catch the exception and do something about it, such as displaying a friendly message or redirect to another page... Also there is a possibility that you can handle the validation by yourself...
Display friendly message: