C#: Enable Cookie Container on System.Net.WebClient (for Authentication)

As I told on the previous post the WebClient can be easily extended to add more functionality such in this case the Cookie Container, and let use it to authenticate versus the web pages that are protected using an authenticated cookie:

public class CookieWebClient : WebClient
	public CookieContainer CookieContainer { get; private set; }

	/// <summary>
	/// This will instanciate an internal CookieContainer.
	/// </summary>
	public CookieWebClient()
		this.CookieContainer = new CookieContainer();

	/// <summary>
	/// Use this if you want to control the CookieContainer outside this class.
	/// </summary>
	public CookieWebClient(CookieContainer cookieContainer)
		this.CookieContainer = cookieContainer;

	protected override WebRequest GetWebRequest(Uri address)
		var request = base.GetWebRequest(address) as HttpWebRequest;
		if (request == null) return base.GetWebRequest(address);
		request.CookieContainer = CookieContainer;
		return request;

And then you can use it as follow:

using (var client = new CookieWebClient())
	var loginData = new NameValueCollection
		{ "UserName", "TestUser" },
		{ "Password", "MyPassword" }

	// Login into the website (at this point the Cookie Container will do the rest of the job for us, and save the cookie for the next calls)
	client.UploadValues("http://domain.com/Account/LogOn", "POST", loginData);

	// Call authenticated resources
	client.UploadString("http://domain.com/ProtectedArea/MyProtectedResource", "POST", "some data");

CookieWebClient takes also a CookieContainer as parameter, to let you control the cookie container outside, and passing over different CookieWebclient instantiation.

4 thoughts on “C#: Enable Cookie Container on System.Net.WebClient (for Authentication)”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: