之前已经有人问过这个问题,但是我没有找到明确的答案。使用System.Net.Http.HttpClient可以获取响应cookies吗?
之前已经有人问过这个问题,但是我没有找到明确的答案。使用System.Net.Http.HttpClient可以获取响应cookies吗?
[Fact]
public async Task Accessing_resource_secured_by_cookie()
{
var handler = new HttpClientHandler();
var httpClient = new HttpClient(handler);
Assert.Equal(0, handler.CookieContainer.Count);
// Create a login form
var body = new Dictionary<string, string>()
{
{"UserName", "<username>"},
{"Password", "<password>"},
{"RememberMe", "false"}
};
var content = new FormUrlEncodedContent(body);
// POST to login form
var response = await httpClient.PostAsync("http://www.nerddinner.com/Account/LogOn?returnUrl=%2F", content);
// Check the cookies created by server
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(1, handler.CookieContainer.Count);
var cookies = handler.CookieContainer.GetCookies(new Uri("http://www.nerddinner.com"));
Assert.Equal(".ASPXAUTH", cookies[0].Name);
// Make new request to secured resource
var myresponse = await httpClient.GetAsync("http://www.nerddinner.com/Dinners/My");
var stringContent = await myresponse.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, myresponse.StatusCode);
}
从代码中可以看出,你无法直接从HTTP响应消息中获取响应cookie。我怀疑HttpClientHandler在返回响应之前会剥离响应头。然而,响应中的cookie已经被放置在CookieContainer中,你可以从那里访问它们。
要获取响应cookie,您可以使用此方法:
private async Task<string> GetCookieValue(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);
var cookie = cookieContainer.GetCookies(uri).Cast<Cookie>().FirstOrDefault(x => x.Name == cookieName);
return cookie?.Value;
}
}
}