Wednesday 3 December 2014

Disabling Asp.Net Request Validation

Asp.Net runtime does check the posted data for any malicious or dangerous contents for security reasons. For example Asp.Net engine considers any html markup, even pretty harmless or small markup like "<b>", as a security threat and blocks the request and throws potentially dangerous value was detected exception.

This is a good thing to block such request because such request can be a severe threat to your website, but there are some scenarios where you would like to accept such contents in the request. For example, you allow users on your website to enter formatted comments or your website is for sharing messages among users then you would like those messages to be formatted, and in that case your website will need to accept the data with html markup.

So what is the solution?

There are two ways:

  1. Allow the html markup for whole website and stop security validation.
  2. Allow the html markup on the specific pages wherever it is required. 
The second option is a good choice because the security is not compromised for whole website.

Disabling security validation is very simple. I have explained it below for both the cases:


For Specific Pages

Add ValidateRequest="false" in the Page directive of the required pages as:

<%@ Page ValidateRequest="false" %>

Add following section into the web.config of your application:
<location path="Common/pageWithUnsecuredData.aspx">
  <system.web>
    <httpRuntime requestValidationMode="2.0" />
  </system.web>
</location>

Set the value of path to a specific page if there is only one page or to a directory path if you want to allow it for more than one pages.

For Whole Website

Add following section into the web.config of your application:
<configuration>
  <system.web>
    <pages validateRequest="false" />
  </system.web>
</configuration>
Add following section into the web.config of your application for each page:
<location path="Common/pageWithUnsecuredData.aspx">
  <system.web>
    <httpRuntime requestValidationMode="2.0" />
  </system.web>
</location>
Set the value of path to a specific page if there is only one page or to a directory path if you want to allow it for more than one pages.
Note: Setting httpRuntime with requestValidationMode="2.0" is required only if you are using Asp.Net 4.0 or above because in these versions the security validation takes place in earlier phase of page life cycle, however, in version 2.0 security validation takes place in later stage of the page life cycle.


No comments:

Post a Comment