简体   繁体   中英

How can I set different config for HttpClientFactory in .NET Core 6

I am using HttpClientFactory for calling my api.

Now I want to use different config for each request, but in my code, I have one place for setting up my config.

My code is like this:

services.AddHttpClient(config =>
    {
        config.BaseAddress = new Uri("https://localhost:5001/api/");
        config.Timeout = new TimeSpan(0, 0, 60);
        config.DefaultRequestHeaders.Clear();
    });

How can I change this config for each request and don't use the same config for all request?

Thanks a bunch

Actually you can use named or typed httpClientFactory for defining special config for each requset,,below are some example code for using named httpclient factory approch,,

you can define your config in program in .net 6 or startup in .net 5 as below

private static void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient("yourHttpClientFactoryName", config =>
    {
        config.BaseAddress = new Uri("https://localhost:5001/api/");
        config.Timeout = new TimeSpan(0, 0, 30);
        config.DefaultRequestHeaders.Clear();
    });

    ...
    
}

As you can see we use name for our configuration,, after that you can use from named httpclientfactory like this

private async Task GetTestWithHttpClientFactory()
{
    var httpClient = _httpClientFactory.CreateClient("CompaniesClient");

    using (var response = await httpClient.GetAsync("companies", HttpCompletionOption.ResponseHeadersRead))
    {
        response.EnsureSuccessStatusCode();

        var stream = await response.Content.ReadAsStreamAsync();

        var companies = await JsonSerializer.DeserializeAsync<List<TestDto>>(stream, _options);
    }
}

you can also use typed approch,, best regard..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM