Search code examples
c#cookieshttpclientfiddleruwp

HttpClient is sending extra cookies


Running a UWP app*

So I have an HttpClient and it's associated handler. I am making a request to a website, passing in specified headers, and using a specified CookieContainer, which is empty at the beginning of the request.

When I send the request, Fiddler shows extra cookies being sent that I have not added. Where are they coming from?

CookieContainer cookieJar = new CookieContainer();                
HttpClientHandler handler = new HttpClientHandler( );
handler.UseDefaultCredentials = false;
handler.CookieContainer = cookieJar;
handler.Proxy = null;
using (var client = new HttpClient(handler as HttpClientHandler))
{
    HttpResponseMessage response = new HttpResponseMessage();
    String loginUrl = Const.BUNGIE_LOGIN_URI + (provider == Const.XBOX_PLATFORM ? Const.XBOX_LOGIN : Const.PS_LOGIN);
    client.BaseAddress = new Uri(loginUrl);
    //client.Timeout = new TimeSpan(0, 0, 0, 0, 450);
    client.DefaultRequestHeaders.Add("Referer", "http://www.bungie.net");
    client.DefaultRequestHeaders.Add("User-Agent", Const.USERAGENT);
    client.DefaultRequestHeaders.Add("X-API-Key", Const.X_API_KEY);
    client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
    client.DefaultRequestHeaders.Add("Accept", "application/json");
    client.DefaultRequestHeaders.Add("Accept-Language", "en-GB,en-US;q=0.8,en;q=0.6");
    handler.AutomaticDecompression = DecompressionMethods.GZip;

    response = client.GetAsync("").Result;
    response.ReadCookies(); //adds cookies to cookieJar
 }

What fiddler shows

Now, as the associated CookieContainer is empty before the request is made, where are these cookies coming from? Are they accessible? If I wanted the values from them, how would I obtain them?

Edit: Where are they being added to my HttpClient request from? Does HttpClient have a common CookieContainer / cache? I have two separate HttpClient instances, and when Client (A) makes a request, it received a "set-cookie" header back, setting a "bungled" cookie.

Later on, a separate instance of HttpClient, Client (B), makes a request to the same website, sending the cookie set within Client (A).

I did not explicitly append this cookie to Client (B)'s request, so how is it being added?


Solution

  • On Windows 10 build 10240, System.Net.Http.HttpClient is a wrapper on top of Windows.Web.Http.HttpClient (more info here), and so, cookies now work little bit different.

    To delete those extra cookies, you will need to delete the cookies using a HttpCookieManager:

    HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
    HttpCookieManager cookieManager = filter.CookieManager;
    foreach (HttpCookie cookie in cookieManager.GetCookies(uri))
    {
        cookieManager.DeleteCookie();
    }