Makavana Pradip
Makavana Pradip

Reputation: 55

ASP.NET Core dependency injection add multiple HttpClient

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?

Upvotes: 4

Views: 9993

Answers (1)

Dimitris Maragkos
Dimitris Maragkos

Reputation: 11392

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

Upvotes: 9

Related Questions