Saturday, 6 July 2013

Potentially dangerous Request.Form value was detected from the client




'A Potentially dangerous Request.Form value was detected from the client'

This is a common error that ASP.NET developers have run into many times. We will see in this post a few ways on how to avoid it. 

Reason
       By default, ASP.NET performs request validation to prevent people from uploading HTML markup or script to your site. ASP.NET checks the content of the form sent to the server to prevent cross-site scripting(xss).  

This error is caused by a newly introduced feature of .NET Framework 1.1, called "Request Validation."  This feature is designed to help prevent script-injection attacks whereby client script code or HTML is unknowingly submitted to a server, stored, and then presented to other users.

Note that anything between '<' and '>' is considered dangerous, and it doesn't have to necessarily closes the tag with '<' ("<a" would have be considered potentially dangerous). ASP.NET validates query string as well.

Try it:
To overcome this error first try to disable the request validation feature, because the validation is done by ASP.NET before any of your code.
<%@ Page ValidateRequest="false" %>

Or you can disable it for your entire application in the web.config file:
<configuration>
    <system.web>
        <pages validateRequest="false" />
    </system.web>
</configuration>

ASP.Net 4.0?
        In ASP.Net 2.0, request validation is enabled for only ASP.Net pages and validated when those pages are executing. Whereas in ASP.Net 4.0, by default request validation is enabled for all requests. As a result validation applies to not only to ASP.Net pages but also to the Web service calls, Http handlers etc.. To prevent this error simply revert ASP.Net behavior back to 2.0. 
To do this, add a configuration element in Web.Config.
<httpRuntime requestValidationMode="2.0" />