Monday, October 26, 2015

A potentially dangerous Request.Form value was detected from the client occurred in ASP.NET 4.0



Error


Problem :
         If you are using ASP.NET 4.0 and  you tried to enter some non-encoded HTML content/text like "( )&< > " in Textbox then browser throws "A potentially dangerous Request.Form value was detected from the client" exception

Cause :
        ASP.Net By default validates all input controls for potentially unsafe contents and you entered text is non-encoded HTML content which is like mark-up text, Thus it disallows such content by throwing the above Exception. By default it is recommended to allow this check to happen on each postback

Resolution :
        There are following resolution for this error
1. In many cases if you want to all such mark-up text to any particular page then you can take use of page directive and make 'ValidateRequest '  to false in page directive
see below snippet
<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest = "false" %>

2. If you want to disable this check throughout your Web Application you’ll need to set it false in your web.config section, see below snippet
 <system.web>
      <pages validateRequest="false" />
 </system.web>

3. You can allow mark-up as input for specific pages instead of the whole site by putting it all in a <location> element. This will make sure all your other pages are safe, see below web.config file
<location path="Code/.aspx">
    <system.web>
      <pages validateRequest="false" />
    </system.web>
  </location>
Above snippet will take care of your all .aspx pages inside Code folder

4. If you are using ASP.NET 4.0 then above all solutions will not help you alone, you need to take help of more settings, you need to keep your requestValidationMode to 2.0, see below web.config snippet
  <location path="Code/.aspx">
    <system.web>
      <pages validateRequest="false" />
      <httpRuntime requestValidationMode="2.0" />
    </system.web>
  </location>

Just re-start your IIS and your problem is resolved !!!