在ASP.NET Core 2.2 Web API中,我希望能够从命名的CookieContainer
访问HttpClient
,并且不确定如何配置它。
在Startup.cs中:
services
.AddHttpClient("MyClient")
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
UseProxy = false,
//CookieContainer = ???
});
在控制器中:
public MyController(IOptions<IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task<ObjectResult> Get<T>(string endpoint)
{
var httpClient = _httpClientFactory.CreateClient("MyClient");
var response = await httpClient.GetAsync($"{Settings.Url}/{endpoint}");
//httpClient.CookieContainer ???
}
仅使用HttpClient
的实例并将CookieContainer
与它的MessageHandler
关联起来非常简单,例如:
var cookieContainer = new CookieContainer();
var handler = new HttpClientHandler() { CookieContainer = cookieContainer };
var client = new HttpClient(handler) { BaseAddress = "http://foo.com/api"}
var result = await client.PostAsync("", content);
//read response cookies
var cookies = cookieContainer.GetCookies(new Uri("http://foo.com/api"));
想知道如何通过使用HttpClient
创建的IHttpClientFactory
实例读取响应cookie。
答案 0 :(得分:2)
这不是CookieContainer
实例,但是您可以在响应标头中访问原始cookie:
var cookies = response.Headers.GetValues("Set-Cookie");
您可以尝试在浏览器中打开Mozilla dev tool来调用您的请求,以查看请求是否确实存在。