Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure HttpClient base address in Blazor Server using IHttpClientFactory

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?

like image 625
Mihaimyh Avatar asked Jan 25 '23 18:01

Mihaimyh


1 Answers

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; }   
        
    }
like image 198
Brian Parker Avatar answered Jan 30 '23 01:01

Brian Parker