返回的 HttpClient 没有我保存到服务集合中的配置

Returned HttpClient does not have the configuration I saved into the service collection

对于 asp.net Web 表单应用程序,我正在尝试从 httpclientfactory 生成 httpclient。但是返回的httpclient并没有我在GetHttpClientFactory方法中配置的配置(基地址和headers)。

public static class HttpClientFactory
{
    private static IHttpClientFactory _httpClientFactory;
    private const string _ClientKey = "MyClient";

    public static IHttpClientFactory GetHttpClientFactory()
    {
        if (_httpClientFactory != null)
        {
            return _httpClientFactory;
        }
        var serviceCollection = new ServiceCollection();

        serviceCollection.AddHttpClient(_ClientKey, client =>
            {
                client.BaseAddress = new Uri("http://localhost:36338");
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("User-Agent", "Demo");
            })
            .ConfigurePrimaryHttpMessageHandler(() =>
                new HttpClientHandler
                {
                    Credentials = new NetworkCredential("accountname", "password")
                });
        var serviceProvider = serviceCollection.BuildServiceProvider();
        _httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
        
        return _httpClientFactory;
    }

}

这是我调用工厂生成客户端的地方。

protected async void Page_Load(object sender, EventArgs e)
    {
        //RegisterAsyncTask(new PageAsyncTask(GetDivisions));
        var loggerFactory = LoggerFactory.Create(builder => {
            builder.AddFilter("Microsoft", LogLevel.Warning);
            });
        var httpClient = HttpClientFactory.GetHttpClientFactory();
        var commonServices = new ServiceWrapper(loggerFactory.CreateLogger<ServiceWrapper>(), httpClient);
        var divisions = await commonServices.GetDivisions();
        foreach (var d in divisions)
            AddTableRow(Table1, d.Id, d.Name);
    }

每次发出 Web 请求时,我都会收到“提供了无效的请求 URI”的异常。

我非常确定您是在未提供客户名称的情况下致电 CreateClient。在 ServiceWrapper:

中尝试下一步
// 1. not sure how the second parameter of ServiceWrapper is called
// 2. Possibly make HttpClientFactory._ClientKey public so no need for magic string
var result = httpClientFactory.CreateClient("MyClient");