此问题曾被问过几次,但我找不到明确的答案。甚至可以使用System.Net.Http.HttpClient获取响应cookie吗?
答案 0 :(得分:5)
下面是我用于访问服务器生成的cookie的一些示例代码。我刚试过它,它对我有用。我改变了凭证。如果你想看到它工作,你需要创建一个nerddinner帐户。
[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中,您可以从那里访问它们。
答案 1 :(得分:1)
要获取响应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;
}
}
}