如何从HttpResponseMessage读取cookie? [英] How to read cookies from HttpResponseMessage?
本文介绍了如何从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;
推荐答案
我在这里有很多答案的问题是使用 CookieContainer
使用不推荐使用的 HttpClient
短寿命对象。
The issue I have with many of the answers here is that using CookieContainer
uses short-lived HttpClient
objects which is not recommended.
相反,您可以简单地从响应中读取 Set-Cookie
标头:
Instead, you can simply read the "Set-Cookie"
header from the response:
// 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;
这篇关于如何从HttpResponseMessage读取cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文