5

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

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

异常截图

任何人都知道这里可能是什么问题?

4

2 回答 2

10

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

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; }   
        
    }
于 2020-09-10T16:09:58.577 回答
1

将此添加到服务中:

    var baseAddress = "http://address-goes-here/";
    services.AddScoped(sp =>
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri(baseAddress);
        return client;
    });
于 2020-11-14T02:32:15.490 回答