4
services.AddHttpClient("Name", client =>
    {
        client.DefaultRequestHeaders.AcceptLanguage.Clear();
        client.BaseAddress = new Uri('BaseUrl');
    })
    .AddAuthenticationHandler(config).Services
    .AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
        .CreateClient('ClientName'));
public partial class StudentClient : IStudentClient
{
    private System.Net.Http.HttpClient _httpClient;

    public UsersClient(System.Net.Http.HttpClient httpClient)
    {
        _httpClient = httpClient;
    }
} 

Right now I have given a code to use HttpClient for accessing services. Now the problem is I have multiple base URLs to call different services and I need to configure that as well. so how can I implement it?

1 Answer 1

9

You can have multiple named http clients:

services.AddHttpClient("Name", client =>
{
    client.DefaultRequestHeaders.AcceptLanguage.Clear();
    client.BaseAddress = new Uri('BaseUrl');
});

services.AddHttpClient("GitHub", client =>
{
    client.BaseAddress = new Uri("https://api.github.com/");
});

Access a specific client using IHttpClientFactory:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private readonly IHttpClientFactory _httpClientFactory;

    public WeatherForecastController(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var httpClient = _httpClientFactory.CreateClient("GitHub");
        
        // use the http client to fetch data
    }
}

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0#named-clients

Sign up to request clarification or add additional context in comments.

1 Comment

doing this seems like the IHttpClientFactory type is not registered on container so the application throws an exception. If i inject the HttpClient type directly works correctly but i can't define the specific client i want to use

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.