web-dev-qa-db-ja.com

HttpResponseMessageからCookieを読み取る方法は?

これは私の最近のコードです:

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;
18
mmh18

これを試して:

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>();
9
RagtimeWilly

これは、Cookieのリストを取得するために必要なものです。

    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;
            }
        }
    }

cookie値が1つだけ必要な場合は、次のようにします

 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;
                }
            }
        }
3
Alper Ebicoglu

ここでの答えの多くで私が抱えている問題は、CookieContainerを使用すると 短命のHttpClientオブジェクトが推奨される を使用することです。

代わりに、"Set-Cookie"レスポンスのヘッダー:

// httpClient is long-lived and comes from a IHttpClientFactory
HttpResponseMessage response = await httpClient.GetAsync(uri);
IEnumerable<string> cookies = response.Headers.SingleOrDefault(header => header.Key == "Set-Cookie")?.Value;
2
Daniel