web-dev-qa-db-fra.com

Comment lire les cookies de HttpResponseMessage?

Ceci est mon code récent:

HttpClient authClient = new HttpClient();
authClient.BaseAddress = new Uri("http://localhost:4999/test_db/_session");
authClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var user = new LoginUserSecretModel
{
    name = userKey,
    password = loginData.Password,
};
HttpResponseMessage authenticationResponse = authClient.PostAsJsonAsync("", user).Result;
13
mmh18

Essaye ça:

CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;

HttpClient authClient = new HttpClient(handler);

var uri = new Uri("http://localhost:4999/test_db/_session");

authClient.BaseAddress = uri;
authClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var user = new LoginUserSecretModel
{
    name = userKey,
    password = loginData.Password,
};

HttpResponseMessage authenticationResponse = authClient.PostAsJsonAsync("", user).Result;

var responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
7
RagtimeWilly

C'est ce dont vous avez besoin pour obtenir une liste de cookies.

    private async Task<List<Cookie>> GetCookies(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);
                List<Cookie> cookies = cookieContainer.GetCookies(uri).Cast<Cookie>().ToList();
                return cookies;
            }
        }
    }

et si vous avez besoin d'une seule valeur de cookie, voici comment

 private async Task<string> GetCookieValue(string url)
        {
            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;
                }
            }
        }
1
Alper Ebicoglu