【问题标题】:How to read cookies from HttpResponseMessage?如何从 HttpResponseMessage 读取 cookie?
【发布时间】:2015-03-24 03:52:31
【问题描述】:

这是我最近的代码:

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;

【问题讨论】:

  • 无论如何,不​​要使用Result。请改用await authClient.PostAsJsonAsync()

标签: c# cookies asp.net-web-api dotnet-httpclient


【解决方案1】:

我对这里的许多答案的问题是使用CookieContainer 使用short-lived HttpClient objects which is not recommended

相反,您可以简单地从响应中读取 "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;

【讨论】:

  • 一旦我们得到“cookies”字符串,有没有一种干净的方法来获取特定的cookie值?必须解析字符串以提取实际的 cookie 值感觉有点笨拙。我认为 .Net 中可能有一个辅助方法来处理它,但是我的大部分研究都回到了 CookieContainer 上,我们在重用我们的 HttpClient 实例时不能使用它。
  • 如果一个人想要同时获得响应和来自该响应的 cookie,则为最佳答案。在我看来,解析字符串是微不足道的。
  • KeyValuePair 不可为空
【解决方案2】:

试试这个:

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

【讨论】:

  • 谢谢你的回答....但是当我得到 HttpResponseMassage 时,“cookie”计数为 0,没有任何内容。
  • 您确定设置了 cookie 吗?
  • 是的,我已经设置好了,我发现 cookie 在 authenticationResponse.headers 中。
  • cookies 安全吗?见这里:stackoverflow.com/questions/14681144/…
  • 另外,如果您使用 HttpClient 作为许多并行请求的共享实例(推荐 aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong ),请注意处理程序中的 cookie 可能属于不同的并行响应,而不是一个你刚收到的。除非您对每个请求都进行一些锁定以避免此类 cookie 竞争条件。
【解决方案3】:

这是获取 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 值,方法如下

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

【讨论】:

    【解决方案4】:

    Daniel's answerthis answer to another question 之上构建,这将是一种从 HTTP 响应中读取 cookie 的简单方法。

    // httpClient is long-lived and comes from a IHttpClientFactory
    HttpResponseMessage response = await httpClient.GetAsync(uri);
    CookieContainer cookies = new CookieContainer();
    foreach (var cookieHeader in response.Headers.GetValues("Set-Cookie"))
        cookies.SetCookies(uri, cookieHeader);
    string cookieValue = cookies.GetCookies(uri).FirstOrDefault(c => c.Name == "MyCookie")?.Value;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 2016-12-02
      • 1970-01-01
      相关资源
      最近更新 更多