Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get response cookies using System.Net.Http.HttpClient?

This question has been asked a few times before, but I could not find a definite answer. Is it even possible to get response cookies using System.Net.Http.HttpClient?

like image 460
Alex I Avatar asked Jul 02 '15 19:07

Alex I


2 Answers

Below is some sample code I have used for accessing server generated cookies. I just tested it and it worked for me. I changed the credentials though. If you want to see it working you will need to create yourself a nerddinner account.

    [Fact]
    public async Task Accessing_resource_secured_by_cookie()
    {
        var handler = new HttpClientHandler();
        var httpClient = new HttpClient(handler);

        Assert.Equal(0, handler.CookieContainer.Count);

        // Create a login form
        var body = new Dictionary<string, string>() 
        {
            {"UserName",  "<username>"},
            {"Password", "<password>"},
            {"RememberMe", "false"}
        };
        var content = new FormUrlEncodedContent(body);

        // POST to login form
        var response = await httpClient.PostAsync("http://www.nerddinner.com/Account/LogOn?returnUrl=%2F", content);

        // Check the cookies created by server
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        Assert.Equal(1, handler.CookieContainer.Count);
        var cookies = handler.CookieContainer.GetCookies(new Uri("http://www.nerddinner.com"));
        Assert.Equal(".ASPXAUTH", cookies[0].Name);

        // Make new request to secured resource
        var myresponse = await httpClient.GetAsync("http://www.nerddinner.com/Dinners/My");

        var stringContent = await myresponse.Content.ReadAsStringAsync();
        Assert.Equal(HttpStatusCode.OK, myresponse.StatusCode);
    }

As you can see from the code, you don't get response cookies directly from the HTTP Response message. I suspect the HttpClientHandler strips the header off the response before returning it. However, the cookies from the response are placed in the CookieContainer and you can access them from there.

like image 156
Darrel Miller Avatar answered Jan 03 '23 00:01

Darrel Miller


to get a response cookie you can use this method;

private async Task<string> GetCookieValue(string url, string cookieName)
{
    var cookieContainer = new CookieContainer();
    var uri = new Uri(url);
    using (var httpClientHandler = new HttpClientHandler
    {
        CookieContainer = cookieContainer
    })
    {
        using (var httpClient = new HttpClient(httpClientHandler))
        {
            await httpClient.GetAsync(uri);
            var cookie = cookieContainer.GetCookies(uri).Cast<Cookie>().FirstOrDefault(x => x.Name == cookieName);
            return cookie?.Value;
        }
    }
}
like image 34
Alper Ebicoglu Avatar answered Jan 02 '23 23:01

Alper Ebicoglu