Monday, December 31, 2012

CookieContainer for HttpWebRequest

Happy New Year!

Are you making a series of HttpWebRequests where you need to persist cookies? For example, perhaps you are experiencing an infinite series of authentication hops. Don't worry, this is very easy to resolve by using the System.Net.CookieContainer class.

xUnit Example

[InlineData("", 0)]
[InlineData("", 2)]
[InlineData("", 8)]
public void CookieJarCount(string requestUriString, int expectedCookieCount)
    var request = (HttpWebRequest) HttpWebRequest.Create(requestUriString);
    // Create a CookieContainer and assign it to the request.
    var cookieJar = new CookieContainer(); 
    request.CookieContainer = cookieJar;
    // Make the request like normal.
    var response = (HttpWebResponse) request.GetResponse();
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    // Let's see how many cookies are in the cookie jar!
    Assert.Equal(expectedCookieCount, cookieJar.Count);
Shout it


Real Time Web Analytics