How do I get response cookies using System.Net.Http.HttpClient?

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

+3


source to share


1 answer


Below is the sample code that I used to access the generated server. I just tested it and it worked for me. However, I changed the credentials. If you want to see it work, you 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 are not getting response cookies directly from the HTTP Response message. I suspect the HttpClientHandler removes the header from the response before returning it. However, the cookies from the response are placed in the CookieContainer and you can access them from there.

+5


source







All Articles