这是我最近的代码:
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;
答案 0 :(得分:14)
我在这里遇到的许多问题是,使用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;
答案 1 :(得分:7)
试试这个:
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>();
答案 2 :(得分:2)
这是获取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;
}
}
}