1

I have lots of HttpClient dependency-injected services. I use an HttpClientFactory to get these.

There are variations, but in a simple case:

// Configure a named and configured HTTP client called "MyHttpClient"
var httpClientBuilder = services.AddHttpClient("MyHttpClient", (sp, client) => /* configure the client */);

...

// Set up the DI service with a factory that gets the named "MyHttpClient"
services.AddTransient<ICustomService>(
    s => 
        new CustomService(
            s.GetRequiredService<IHttpClientFactory>().CreateClient("MyHttpClient")));

I have a service that responds with Set-Cookie headers (in this case AWSALB load balancing indicators from AWS, but this question is for any cookies) - I want the HttpClient to respond with these cookies.

I can take that httpClientBuilder and use it to create a custom handler that sets up a CookieContainer to do this, but it feels like re-inventing the wheel.

Is there an existing solution for this? Something like:

services.AddHttpClient(...)
    .AddCookieHandler(); // Automatically set up `CookieContainer` for all requests

1 Answer 1

0

We can use ConfigurePrimaryHttpMessageHandler to implement this feature, here is the sample code.

builder.Services.AddHttpClient("MyHttpClient", client =>
{
    client.BaseAddress = new Uri("https://yoursite.com");
    client.DefaultRequestHeaders.Add("Accept", "application/json");
})
.ConfigurePrimaryHttpMessageHandler(() =>
{
    var handler = new HttpClientHandler();
    if (handler.SupportsAutomaticDecompression)
    {
        handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    }
    handler.CookieContainer = new CookieContainer();  
    return handler;
});
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I mentioned this in the question, but it feels like reinventing the wheel - this sample is a start, but now you need to manage that CookieContainer too (is it global, per user, are there cookies it should ignore, etc) and this is very boilerplate stuff. It seems weird there's no easier/best practice way to do this?
Also, why did you edit the tag to asp.net-core? I'm testing a DI service in a console app and calling a 3rd party on AWS, ASP has nothing to do with it.
Hi @Keith, Because your question mentioned cookies, I thought you were using web-related technologies, so I added the asp.net-core tag. At the same time, I also think that the issues you are concerned about are also applicable to asp.net-core related areas.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.