How to configure HttpClient base address in Blazor Server using IHttpClientFactory

18.2k Views Asked by At

I am trying to configure HttpClient 's base address in a Blazor Server using IHttpClientFactory but I am getting a runtime exception:

    services.AddHttpClient("ApiClient", (provider, client) =>
    {
        var uriHelper = provider.GetRequiredService<NavigationManager>();
        client.BaseAddress = new Uri(uriHelper.BaseUri);
    });
System.InvalidOperationException: 'Cannot resolve scoped service 'Microsoft.AspNetCore.Components.NavigationManager' from root provider.'

Exception screenshot

Anyone know what might be the issue here?

3

There are 3 best solutions below

8
On BEST ANSWER

The base url is not available during ConfigureServices you can pass it or create a service :

services.AddHttpClient();
services.AddTransient<ApiService>();

The service:

public class ApiService
{
    public ApiService(HttpClient httpClient, NavigationManager navigationManager)
    {
        HttpClient = httpClient;
        NavigationManager = navigationManager;
        HttpClient.BaseAddress = new Uri(NavigationManager.BaseUri);
    }

    public HttpClient HttpClient { get; }
    public NavigationManager NavigationManager { get; }
}

A component:

   Base Address : @ApiService.HttpClient.BaseAddress
        
    @code {
        [Inject]
        public ApiService ApiService { get; set; }   
        
    }
0
On

Great answer John. This is the same solution but simpler:

services.AddScoped(sp => new HttpClient 
    { 
        BaseAddress = new Uri("https://localhost:7110/") 
    });
0
On

Add this to the services:

    var baseAddress = "http://address-goes-here/";
    services.AddScoped(sp =>
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri(baseAddress);
        return client;
    });