16.3. Simulating Form Execution

Problem

You need to send a collection of name-value pairs to simulate a form being executed on a browser to a location identified by a URL.

Solution

Use the System.Net.WebClient class to send a set of name-value pairs to the web server using the UploadValues method. This class enables you to masquerade as the browser executing a form by setting up the name-value pairs with the input data. The input field ID is the name, and the value to use in the field is the value:

	    using System;
	    using System.Net;
	    using System.Text;
	    using System.Collections.Specialized;

	// In order to use this, you need to run the CSCBWeb project first.
	Uri uri = new Uri("http://localhost:7472/CSCBWeb/WebForm1.aspx");
	WebClient client = new WebClient();

	// Create a series of name/value pairs to send
	// Add necessary parameter/value pairs to the name/value container.
	NameValueCollection collection = new NameValueCollection()
	            { {"Item", "WebParts"},
	              {"Identity", "foo@bar.com"},
	              {"Quantity", "5"} };
	Console.WriteLine("Uploading name/value pairs to URI {0} ...",
	    uri.AbsoluteUri);

	// Upload the NameValueCollection
	byte[] responseArray =
	     client.UploadValues(uri.AbsoluteUri,"POST",collection);
	// Decode and display the response.
	Console.WriteLine("\nResponse received was {0}",
	            Encoding.ASCII.GetString(responseArray));

The WebForm1.aspx page, which receives and processes this data, looks like this:

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm1.aspx.cs" Inherits="WebForm1" ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.