Exception message: A potentially dangerous Request.Form value was detected from the client

A recent requirement was to transfer XML documents via HTTP Post on the dotNET 2.0 platform. I had set up the “application” to receive the XML stream and save the data as a file (Sample codes demonstrates reading location from config and saving the stream; content validation not shown).
protected void Page_Load(object sender, EventArgs e)
        {
            using (System.IO.StreamReader reader = new System.IO.StreamReader(Request.InputStream))
            {
                String xmldata = reader.ReadToEnd();
                Response.ContentType = "text/xml";
                //Response.Write(xmldata);
                Response.Write(String.Format("Bytes received: {0}", xmldata.Length));

                string myConfigValue = WebConfigurationManager.AppSettings["DropOffFolder"];
                if (System.IO.Directory.Exists(myConfigValue))
                {
                    Guid g = new Guid();
                    g = Guid.NewGuid();
                    string filename = myConfigValue + g.ToString() + ".xml";
                    //Response.Write(filename);
                    using (StreamWriter sw = new StreamWriter(filename))
                    { sw.Write(xmldata); }
                }

                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.Flush();
                Response.End();
                Response.Close();
            }
        }
 
During testing I had sent successfully exchanged text data. However, when I tried to send XML data I received a 500 response error from the server, which is very generic.  I reviewed the event log on the server to see if IIS logged any messages and noticed the following warning:
Exception information:
    Exception type: HttpRequestValidationException
    Exception message: A potentially dangerous Request.Form value was detected from the client.

 

The server was validating the data stream, which is uuencoded HTML. To bypass this particular validation I added  ValidateRequest="false to the page directive. The ValidateRequest attribute checks for potentially dangerous input data that could compromise the security of your application or a scripting attack.

 

Note:  When ValidateRequest is disabled, content can be submitted to your application; it is the responsibility of the application developer to ensure that content is properly encoded or processed.

Another way to process the data, without having to disable validation, would be to encode and decode it using Server.HtmlEncode(string) and Server.HtmlDecode(string).



   

C#: ASP.NET CAPTCHA

As easy as it is to develop a web form that accepts user input, it is just as easy to develop an automated application that can fill the web form with data. In an attempt defend against these applications; web authors often implement a challenge-response mechanism to verify that the web form has been completed by a “human”. This challenge-response mechanism is commonly referred to as CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart). The key to a CAPTCHA mechanism is to make it easy for humans and difficult for “computers” to solve. One popular method is to generate random text for a human to enter as part of the data entry process.

CAPTCHA

There are many commercial and free CAPTCHA plugins available for use, but you can easily create a CAPTCHA as part of your web application. To incorporate your own CAPTCHA mechanism into your web form:

- Add a method to generate the “random text”

public void SetCAPTCHAText()
    {
        // generate a random number
        Random ran = new Random();
        int no = ran.Next(11111, 99999);
        // store the random number in a session variable
        Session["Captcha"] = no.ToString();
    }

Add a method to validate the “random text” with user input

protected void CAPTCHAValidate(object source, ServerValidateEventArgs args)
    {

        if (Session["Captcha"] != null)
        {
            if (txtVerify.Text.ToUpper() != Session["Captcha"].ToString().ToUpper())
            {
                SetCAPTCHAText();
                args.IsValid = false;
                return;
            }
        }
        else
        {
            SetCAPTCHAText();
            args.IsValid = false;
            return;
        }

    }

- Add a new Generic Handler to your Web Site to draw the image containing the “random text”

Generic Handler
public void ProcessRequest(HttpContext context)
    {
        //factor for scaling
        int factor = 25;

        // set the size of the image
        int imagewidth = 150;
        int imageheight = 30;

        // setup the image
        Bitmap bmpOut = new Bitmap(imagewidth, imageheight);
        Graphics g = Graphics.FromImage(bmpOut);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        g.FillRectangle(Brushes.White, 0, 0, imagewidth, imageheight);

        // draw the verification code on the image
        Color c = new Color();
        c = Color.Black;
        Font f = new Font("Verdana", 14);
        SolidBrush b = new SolidBrush(c);
        if (!String.IsNullOrEmpty(System.Web.HttpContext.Current.Session["Captcha"].ToString()))
        {
            g.DrawString(System.Web.HttpContext.Current.Session["Captcha"].ToString(), f, b, 5, 5);
        }

        // draw some random data to image to distort OCR
        Random rnd = new Random();
        int m = imagewidth / factor;
        for (int i = 0; i <= Convert.ToInt32(Math.Truncate(bmpOut.Width * bmpOut.Height / (double)factor)) - 1; i++)
        {
            int x = rnd.Next(bmpOut.Width);
            int y = rnd.Next(bmpOut.Height);
            int w = rnd.Next(m);
            int h = rnd.Next(m);
            g.FillEllipse(Brushes.Gray, x, y, w, h);
            
            // you could get creative with other "noise"
            //Point[] points = { new Point(100, 25), new Point(90, 20), new Point(110, 15), new Point(85, 15) };
            //g.FillClosedCurve(Brushes.Red, points);
        }

        // write the image to the stream for display on the webpage
        MemoryStream ms = new MemoryStream();
        bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        byte[] bmpBytes = ms.GetBuffer();
        bmpOut.Dispose();
        g.Dispose();
        ms.Close();
        context.Response.BinaryWrite(bmpBytes);
        context.Response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

- Add an image to the web form to display the CAPTCHA text – the image is drawn by the Handler
- Add a text box for the user input
- Validate the user input when the user submits the form

 
<div>
        <asp:Image ID="imCaptcha" ImageUrl="~/Captcha.ashx" runat="server" /><br />
        <asp:TextBox ID="txtVerify" runat="server"></asp:TextBox>
        <asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="txtVerify"
            ErrorMessage="Invalid verification code entered." OnServerValidate="CAPTCHAValidate"
            SetFocusOnError="True" ValidateEmptyText="True" 
            ToolTip="Invalid verification code entered.">*</asp:CustomValidator><br />
        <asp:Label ID="Label4" runat="server" Text="Enter the number displayed above."></asp:Label><br />
        <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert"
            Text="Submit" />
        <asp:ValidationSummary ID="ValidationSummary1" runat="server" />
    </div>

 

The sample application referenced in this post can be downloaded >>>here<<<.



   

ASP.NET: Programmatically set the InnerHtml of a <div>

To programmatically set the InnerHtml of a <div> control in a web form set the <div> control to runat = ”server”:

<div id="myDIV" runat="server">

With the <div> set to run on the server it is accessible via the codebehind page:

myDIV.InnerHtml = "<font color='red'>Message</font>";