Click here to Skip to main content
15,883,901 members
Articles / Web Development / ASP.NET
Tip/Trick

ASP.NET Disable Request Validation for Single Control

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
5 Jul 2017CPOL2 min read 14.7K   1  
Solution to disable request validation for single control - clean approach and without much effort

Introduction

In an ASP.NET 2.0 application, I had to fix “potentially dangerous request.form” exception. This exception occurs when request validation for application/page is enabled and an ASP.NET page is submitted with un-encoded value such as <script>Hello!</script>. The request validation is by default enabled, but you can simply disable this and you will not see this exception. Below is how you can disable request validation.

Disabling request validation for page:

ASP.NET
<%@ Page validateRequest="false" %>

Disabling request validation for application:

XML
<configuration>
   <system.web>
      <pages validateRequest="false" />
   </system.web>
</configuration>

Please refer to this link for more information on request validation.

However, if you disable request validation, your page and/or application will be vulnerable to script injection and other attacks.

So, to fix this issue, simply disabling request validation is not the solution. If you are disabling the request validation, it is your responsibility to encode every field value, query string, header, etc. before persisting it and decode (as required) before it is displayed on the page. You can use the below code to encode and decode respectively (or you can use some AntiXSS library functions).

JavaScript
HttpUtility.HtmlEncode(value)
HttpUtility.HtmlDecode(value)

Having said this, you would need more efforts to implement and test this change. The efforts are going to be on even more higher side if your page has more controls. Also, if the requirement is to support un-encoded value for single or couple of controls on the page and not all controls, then we would be putting unnecessary efforts with this approach.

To fix this issue without disabling the request validation and with minimal efforts, below is a solution.

The trick is to encode the value to be submitted on client before the page is submitted. This ensures that you are able to submit the page with un-encoded value(s). The important thing to notice here is, we are not disabling the request validation. So, the request validation will not allow the page to be submitted if it has any un-encoded value. This means even if someone intercepts your request and changes the encoded value to un-encoded, still he/she will get “potentially dangerous…” exception.

Solution

Create a custom control which will handle encode/decode of text entered into it (on client and server). To create and utilize this control, perform the below steps:

Step# 1

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CustomApplication
{
    public class CustomTextField : System.Web.UI.WebControls.TextBox
    {
        protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);
            if (!Page.ClientScript.IsClientScriptBlockRegistered(Page.GetType(), "TextBoxEncode"))
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("function EncodeTextFieldValue(id)");
                sb.Append("{");
                sb.Append("var txtbox = document.getElementById(id);");
                sb.Append("txtbox.value = 
                txtbox.value.replace(new RegExp('<', 'g'), '&lt;');");
                sb.Append("txtbox.value = 
                txtbox.value.replace(new RegExp('>', 'g'), '&gt;');");
                sb.Append("txtbox.value = 
                txtbox.value.replace(new RegExp('&', 'g'), '&amp;');");
                sb.Append("}");
                Page.ClientScript.RegisterClientScriptBlock
                           (Page.GetType(), "keyEnc", sb.ToString(), true);
            }

            // Adds the function call after the form validation is called.
            if (!Page.IsPostBack)
                Page.Form.Attributes["onsubmit"] += 
                "EncodeTextFieldValue('" + ClientID + "');";
        }

        public override string Text
        {
            get { return base.Text; }
            set
            {
                if (!string.IsNullOrEmpty(value))
                    base.Text = value.Replace("&amp;lt;", "<").Replace
                                       ("&amp;gt;", ">").Replace("&amp;", "&");
                else
                    base.Text = value;
            }
        }
    }
}

Step# 2

Register your custom control on .aspx page:

ASP.NET
<%@ Register TagPrefix="ctb" Namespace="namespace" 
Assembly="assembly" %>

Step# 3

Add custom text box in your .aspx page:

ASP.NET
<stb:CustomTextBox ID="txtDescription" runat="server" 
TextMode="MultiLine"> </stb:CustomTextBox>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
My name is Ambrish, I am a passionate software developer with rich experience in .Net technologies including vb.net, c#, MVC, Angular JS, jQuery, Windows Services, Asp.net Web Forms, Asp.net Web Api, javascript, entity framework, WCF, windows forms, SQL server.

Currently I am working as a Technical Lead and handling the project from Design, development and mentoring perspectives.

Comments and Discussions

 
-- There are no messages in this forum --