In an ASP.NET Core 2.2 web API, I want to be able to access CookieContainer
from a named HttpClient
and not sure how to configure this.
In Startup.cs:
services
.AddHttpClient("MyClient")
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
UseProxy = false,
//CookieContainer = ???
});
In controller:
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 ???
}
It's pretty straight forward while using just an instance of HttpClient
and associating a CookieContainer
with its MessageHandler
, e.g.:
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"));
Wondering how I can read response cookies but via an instance of HttpClient
created using IHttpClientFactory
.
It has a method CreateClient which returns the HttpClient Object. But in reality, HttpClient is just a wrapper, for HttpMessageHandler. HttpClientFactory manages the lifetime of HttpMessageHandelr, which is actually a HttpClientHandler who does the real work under the hood.
Therefore, HttpClient is intended to be instantiated once and reused throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.
Register an IHttpClientFactory instance in ASP.NET Core You can register an instance of type IHttpClientFactory in the ConfigureServices method of the Startup class by calling the AddHttpClient extension method on the IServiceCollection instance as shown in the code snippet given below.
ConfigurePrimaryHttpMessageHandler(IHttpClientBuilder, Func<IServiceProvider,HttpMessageHandler>) Adds a delegate that will be used to configure the primary HttpMessageHandler for a named HttpClient.
That's not CookieContainer
instance, but you can access raw cookies in response header:
var cookies = response.Headers.GetValues("Set-Cookie");
And you can try to call your request in the browser with open Mozilla dev tool to see if it is truly there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With