如何在通过HTTPClientFactory创建的HTTPClient实例中访问CookieContainer

时间:2019-07-03 22:54:31

标签: c# asp.net-core

在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。

1 个答案:

答案 0 :(得分:2)

这不是CookieContainer实例,但是您可以在响应标头中访问原始cookie:

var cookies = response.Headers.GetValues("Set-Cookie");

您可以尝试在浏览器中打开Mozilla dev tool来调用您的请求,以查看请求是否确实存在。

Mozilla Developer tools