ASP.NET: HttpRequestValidationException on HTTP Post method

Today I developed an aspx page that another company we are integrated with would use to send us some XML data. They transfer the data by performing an HTTP Post to a web page hosted on our servers. To do this I simply read the data posted in the Page_Load event like so:

protected void Page_Load(object sender, EventArgs e)
        if (Request.HttpMethod.ToUpper().Equals("POST"))
            StreamReader reader = new StreamReader(Request.InputStream);                    
            string xml = reader.ReadToEnd();
            XmlDocument xmlDoc = new XmlDocument();
    catch (Exception ex)
        // Handle exception

To test my code I created a simple html form and posted to the page and all worked fantastically. I figured even thought information I was posting from the form wasn’t XML, the concept was the same and all should work accordingly. I moved the code out to our production server but it wouldn’t work for the life of me. Nothing seemed to be working, the Page_Load event didn’t even get fired. I ran Wireshark and I saw the HTTP Post come in but nothing was ever done with it. I then took a look at the Windows Application log files and found the problem. The following exception was being thrown before the Page_Load event event fired:

Exception information: 
    Exception type: HttpRequestValidationException 
    Exception message: A potentially dangerous Request.Form value was detected from the client (<?xml version=""1.0" ?><?adf version="1.0" ..."). 

I had forgotten that the .NET Framework does its own validation on all requests and since the post contained XML which could look like a potentially harmful script, it would not let it through. A great security feature but unfortunately the Page_Load event wasn’t even being fired and thus I couldn’t see the exception right off the bat.

To fix this all you need to do is disable request validation for the page using the following page directive.

<%@ Page Language="C#" ValidateRequest="false" ...%>

Obviously if you do this you should explicitly check all inputs and ensure no one can do anything malicious.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: