如何使用 IHttpClientFactory 在 Blazor Server 中配置 HttpClient 基址

How to configure HttpClient base address in Blazor Server using IHttpClientFactory

我正在尝试使用 IHttpClientFactoryBlazor 服务器中配置 HttpClient 的基地址,但我收到运行时异常:

    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.'

有人知道这里可能是什么问题吗?

基础 url 在 ConfigureServices 期间不可用,您可以传递它或创建服务:

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

服务:

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; }
}

一个组件:

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

将此添加到服务中:

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