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).

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.

Who does not like cookies?

As I was doing some odd exploration of an older ASP application I decided to do some experimentation with cookies. As with most of my posts I try to drop things back significantly allowing for some basic examples. Cookies are a way for a web application to store specific information. Cookies are small text files that are stored on a client machine and are contained in the Response and Request traffic between a client and host computer. Web applications can read cookies whenever a user visits the site. Information such as user preferences could be stored in a cookie.

Within .NET there the HttpCookie Class is used for dealing with cookie information. Basic dealing with cookies is a lot easier than it may initially sound. I was able to put together a sample application that stores a textbox, validated textbox and calendar date (cookies store strings) in a cookie in only a few minutes.

Start a new ASP.NET Web Application from within BDS2006. On the default design form place a two text boxes, a calendar control, a RegularExpressionValidator and three buttons. I also placed some labels for identification.

Set the properties for RegularExpression1 as follows:
// This checks for a proper email address
ValidationExpression:= ‘\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*’;
ControlToValidate:= txtEmail;
ErrorMessage:= ‘Invalid Email’;

The following is the code behind the page (For maintenance, I’d use constants for the value and cookie names):
procedure TWebForm1.Page_Load(sender: System.Object; e: System.EventArgs);
// The calendar defaults to a selected date of 01/01/0001
if Calendar1.SelectedDate = DateTime.Parse('01/01/0001') then
Calendar1.SelectedDate:= DateTime.Now;

procedure TWebForm1.btnClear_Click(sender: System.Object; e: System.EventArgs);
hc: HttpCookie;
if Request.Cookies['MySite'] nil then
hc:= Request.Cookies['MySite'];
// This method may work, however the proper way to clear a cookie
// is to set the cookie to have a prior expiration date
// hc.Values.Clear;
// Response.Cookies.Add(hc);
// Calendar1.SelectedDate:= DateTime.Now;

hc.Expires:= DateTime.Now.AddDays(-100);
txtEmail.Text:= '';
Calendar1.SelectedDate:= DateTime.Now;

procedure TWebForm1.btnRead_Click(sender: System.Object; e: System.EventArgs);
hc: HttpCookie;
if Request.Cookies['MySite'] nil then
txtEmail.Text:= Request.Cookies['MySite'].Values['email'];
txtName.Text:= Request.Cookies['MySite'].Values['name'];
Calendar1.SelectedDate:= DateTime.Parse(Request.Cookies['MySite'].Values['date']);

txtEmail.Text:= '';
txtName.Text:= '';
Calendar1.SelectedDate:= DateTime.Now;

procedure TWebForm1.btnWrite_Click(sender: System.Object; e: System.EventArgs);
hc: HttpCookie;
RegularExpressionValidator1.IsValid then
hc:= HttpCookie.Create('MySite');
hc.Values['name']:= txtName.Text;
hc.Values['email']:= txtEmail.Text;
hc.Values['date']:= Calendar1.SelectedDate.ToShortDateString;
// Expire cookie in 1hour. Always set an expiration
// if you do not set an expiration date the cookie is not
// stored; it will be treated as a session variable
// DateTime.MaxValue will make it last forever
hc.Expires:= DateTime.Now.AddHours(1);

For some more information take a look at ASP.NET Cookies Overview on MSDN. Another valuable link is How to Share Session State Between Classic ASP and ASP.NET.

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.