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(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";
                    using (StreamWriter sw = new StreamWriter(filename))
                    { sw.Write(xmldata); }

                Response.ContentEncoding = System.Text.Encoding.UTF8;
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).


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.


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())
                args.IsValid = false;
            args.IsValid = false;


- 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();

    public bool IsReusable
            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

        <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" />


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>";

ASP.NET Membership Using a Custom Profile

ASP.NET Membership Custom Profile

The ASP.NET Membership is an easy way to manage user credentials and security within ASP.NET Web Application (Web Site).  ASP.NET Membership will not only handle user authentication, it can also be used to manage user profile information.  To add a Custom Profile for the ASP.NET Membership users you need to enable profiles, specify a profile provider and add the profile properties in the system.web section of the web.config file:
<profile enabled="true">
				<remove name="AspNetSqlProfileProvider"/>
				<add name="AspNetSqlProfileProvider" connectionStringName="SqlMembership" applicationName="appProfile" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
				<add name="Gender" type="System.String"/>
				<add name="favoritenumber" type="System.Int32"/>
				<add name="notification" type="System.Boolean"/>
				<add name="BirthDate" type="System.DateTime"/>
Once the profile information has been enable and configured a user’s profile information can be read and saved through the dynamic ProfileCommon class. The ProfileCommon class will the properties specified in the configuration file.  A simplified code example for reading and saving profile values:
protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            if (User.Identity.IsAuthenticated == true)
                MembershipUser user = Membership.GetUser();
                ((TextBox)LoginView1.FindControl("Email")).Text = ((TextBox)LoginView1.FindControl("Email2")).Text = user.Email;
                ((TextBox)LoginView1.FindControl("txtNumber")).Text = Profile.favoritenumber.ToString();
                DropDownList ddl = (DropDownList)LoginView1.FindControl("ddlGender");
                ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(Profile.Gender));
                ((CheckBox)LoginView1.FindControl("chkNotification")).Checked = Profile.notification;

    protected void btnSave_Click(object sender, EventArgs e)
        if (Page.IsValid)
            TextBox Email;
            MembershipUser user = Membership.GetUser();
            Email = (TextBox)LoginView1.FindControl("Email");
            if (user.Email != Email.Text)
                user.Email = Email.Text;
            Profile.Gender = ((DropDownList)LoginView1.FindControl("ddlGender")).SelectedValue;
            Profile.notification = ((CheckBox)LoginView1.FindControl("chkNotification")).Checked;
            Profile.favoritenumber = System.Convert.ToInt32(((TextBox)LoginView1.FindControl("txtNumber")).Text);

ASP.NET Membership Custom Profile

ASP.NET upload a file HtmlInputFile Control

When developing a web application it often may be necessary to allow a user to ‘send’ (upload) a file. With HtmlInputFile control the this seemingly complicated task is much easier than one would expect. The HtmlInputFile control is not listed in the toolbox by default but can be easily added using HTML in your page. In order to use the HtmlInputFile control the following form code must be added to your .aspx page:

<form id="Form1" method="post" runat="server" enctype="multipart/form-data">

<input id="btnSelectFile" type="file" runat="server" style="Z-INDEX: 101; LEFT: 24px; WIDTH: 470px; POSITION: absolute; TOP: 48px; HEIGHT: 22px" size="59">

<asp:Label id="lblStatus" style="Z-INDEX: 103; LEFT: 176px; POSITION: absolute; TOP: 88px" runat="server" Width="224px">Status:</asp:Label>
<asp:Button id="btnUpload" style="Z-INDEX: 102; LEFT: 96px; POSITION: absolute; TOP: 88px" runat="server" Text="Upload"></asp:Button>

The size and position of the controls can be what ever you desire. Once the HtmlInputFile code is added you can visually design its size and position. In the above code I have also included a label for the displaying of status information and a button that will actually execute the code for the uploading of the file selected with the HtmlInputFile.
The code to upload the file is simple:

' Root Data path
‘ ensure the proper permissions are set on this folder default is the ASP.NET account
Const ROOTPATH = "C:\Data\"

Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpload.Click

Dim filename As String

' Extract the selected filename
filename = System.IO.Path.GetFileName(btnSelectFile.PostedFile.FileName)

' Set the label to display where the file will be saved – this could also be used to display the file size uploaded
lblStatus.Text = "Status: " & ROOTPATH & filename

' Save the file
btnSelectFile.PostedFile.SaveAs(ROOTPATH & filename)

' This calls a procedure that I had created that will display the contents of a directory in a table

End Sub

Private Sub ListDirectory()

Dim currentdir As New DirectoryInfo(ROOTPATH)
Dim files As FileInfo
Dim tr As TableRow
Dim tcFile As TableCell
Dim tcSize As TableCell

For Each files In currentdir.GetFiles()
tr = New TableRow
tcFile = New TableCell
tcSize = New TableCell
tcFile.Text = files.Name
tcSize.HorizontalAlign = HorizontalAlign.Right
tcSize.Text = FormatNumber(files.Length, 0, TriState.False, TriState.True, TriState.True)

End Sub

In reviewing the previous code sample one can see how easy it is to upload a file through a web application.

Reading Stuff

Information in this document subject to change without notice.
All Software source code published is for demonstration and knowledge sharing purposes only. The Code is supplied "as is" without warranty as to result, performance or merchantability. Use at your own risk.
The opinions expressed herein are the opinions of the author and do not reflect those of any other entity.