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

[Theory]
[InlineData("http://www.yahoo.com", 0)]
[InlineData("http://www.google.com", 2)]
[InlineData("http://www.bing.com", 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

Enjoy,
Tom

No comments:

Post a Comment

Real Time Web Analytics