ASP.NET ValidateRequest not working

ValidateRequest in ASP.NET is a really good security measure as it prevents cross-site scripting which basically means that it prevents malicious codes from being injected into your application. A typical example would be if you have a textbox on your webpage to capture the name of a visitor and the user enters something the following : <script>alert(‘hello world’);</script> instead of his name, then this could lead to potential hacks. Imagine if your code was to immediately write back the name of the person after submitting the form – instead of writing back the name of the person, the above script would run and an alert box would pop up to say “hello world”. Although this will not cause any problems, people with bad intention can really mess up your application and hack your website as well as the people visiting your site.

This is where ASP.NET ValidateRequest comes into play. When set to true on a page, it will raise an exception if it finds that unsafe html is being sent through your web form. In previous versions of asp.net, you could just add ValidateRequest=”false” if you wanted to turn off this feature but in ASP.NET version 4, you need to add <httpRuntime requestValidationMode=”2.0″ /> to your web.config file under <system.web>. Just including ValidateRequest=”false” in the page directive¬† is not enough because asp.net 4 sets ValidateRequest to true for all requests by default and the only way to set it to false on a page by page basis is to tell asp.net to use the validation mode of asp.net by including the above code in the web.config file.

Although there are scenarios where you want to disable ValidateRequest like if you want people to send code samples or include formatting tags like bold, italics in comments, you need to ensure that you are validating the input on the server side before you process them. You can use htmlencode so that any XSS is rendered harmless.

So if ValidateRequest is not working for you, then make sure that you have included the code above in your web.config if you’re using asp.net 4 runtime environment.

  • Is it just for .net 4.0?

  • You’ll only need to do that if you’re targetting .net framework 4.0.

  • Hmm ok. Thanks for reply.

comments powered by Disqus