Wednesday, March 07, 2007

HttpWebRequest With Cookie Context

I was doing some load test on an ASP.NET page. The page uses Cache to store some profile data, and the Cache is associated with the client Cookie value. The load test tools I have don't have such dynamic cookie assignment functionality. So I created a simple load test tool for this. The key point is to assign the CookieContainer property of the HttpWebRequest object:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace HttpRequestTest
{
class Program
{
static void Main(string[] args)
{
string url = "http://localhost/MyDashBoard.aspx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
CookieContainer cookieContainer = new CookieContainer();
Cookie cookie = new Cookie("cookieKey", "cookieValue");
cookie.Path= "/";
cookie.Domain = "localhost";
cookieContainer.Add(cookie);
request.CookieContainer = cookieContainer;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseData = response.GetResponseStream();
StreamReader reader = new StreamReader(responseData);
string responseFromServer = reader.ReadToEnd();

Console.Read();

}
}
}