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.'
Anyone know what might be the issue here?
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; }
}