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

Lev*_*Lev 10 c# asp.net-core

在 ASP.NET Core 2.2 Web API 中,我希望能够CookieContainer从命名访问HttpClient,但不确定如何配置它。

在 Startup.cs 中:

        services
            .AddHttpClient("MyClient")                
            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
            {
                UseProxy = false,
                //CookieContainer = ???
            });
Run Code Online (Sandbox Code Playgroud)

在控制器中:

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 ???
}
Run Code Online (Sandbox Code Playgroud)

仅使用 的实例HttpClient并将 aCookieContainer与其相关联时,这是非常直接的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"));
Run Code Online (Sandbox Code Playgroud)

想知道如何读取响应 cookie 但通过HttpClient使用IHttpClientFactory.

Svi*_* V. 3

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

var cookies = response.Headers.GetValues("Set-Cookie");
Run Code Online (Sandbox Code Playgroud)

您可以尝试使用打开的Mozilla 开发工具在浏览器中调用您的请求,看看它是否确实存在。

Mozilla 开发者工具