sohil bhalla
sohil bhalla

Reputation: 1

Passing Parameters dynamically to HttpClient based on the request

I have a .NET standard 2.0 class library which is responsible for making all the HttpClient calls from the applications that consume the library.

With all the understanding from the Microsoft documentation on HttpClient, it is advisable and what I am following is to use IHttpClientFactory to create HttpClients to avoid any socket exceptions.

My implementation is I am injecting IHttpClientFactory from my caller application using named client and creating the HttpClient object inside the library.

Caller application code

    builder.Services.AddHttpClient("Default").ConfigurePrimaryHttpMessageHandler((sp) =>
{
    return new HttpClientHandler()
    {
        UseCookies = true
    };
});

Standard Library Code

public class HttpHandlerFactory : IHttpHandlerFactory
{
    private readonly System.Net.Http.IHttpClientFactory httpClientFactory;

    RestfulHandlerConfiguration configuration;
    public HttpHandlerFactory(System.Net.Http.IHttpClientFactory httpClientFactory)
    {
        this.httpClientFactory = httpClientFactory;
    }
    public HttpClient CreateHttpHandler(RestfulHandlerConfiguration configuration)
    {
        this.configuration = configuration;
        var httpClient = httpClientFactory.CreateClient("Default");
        httpClient.Timeout = TimeSpan.FromMilliseconds(configuration.Timeout);
    }

}

In certain cases/caller application there are multiple API calls happening which would require different settings at the HttpClient level (HttpClientFactory).

For example 3 calls out of 10 calls needs UseCookies true, 2 calls needs Credentials as Default Network Credentials etc. My HttpClientHandler Settings are dynamic and will change based on multiple parameters.

I cannot have multiple named clients defined at the start of the application as it will end up in creating so many clients based on the combinations, so how can I have my HttpClientHandler settings set at the time when I Create HttpClient object using IHttpClientfactory and also get the reusability of it when used with IHttpClientFactory.

Upvotes: 0

Views: 705

Answers (0)

Related Questions