c# - .NET 核心 : HttpClientFactory: How to configure ConfigurePrimaryHttpMessageHandler without dependency injection?

标签 c# asp.net-core .net-core dependency-injection httpclient

我有一个 .NET Core 类库。我正在使用 IHttpClientFactory 创建没有依赖注入(inject)的 HttpClient 实例。我在我的类库中包含了 Microsoft DI nuget 包。

示例代码#1:

Class A {

private readonly HttpClient client;

 public A(){
            var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
            var _httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
            client = _httpClientFactory.CreateClient();  //HttpClient instance created
            //TODO: Add custom message handler without DI.
  }
}

使用 DI,我们可以配置自定义消息处理程序: 带有 DI 的示例代码#2:

services.AddHttpClient()
        .ConfigurePrimaryHttpMessageHandler(() =>
        {
            return new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (m, crt, chn, e) => true
            };
        });

我想在没有 DI 的情况下将 HttpClientHandler 添加到我的示例代码 #1。 如何在没有 DI 的情况下配置主消息处理程序?

最佳答案

我认为你的设置很奇怪,但除此之外,你可能可以做这样的事情:

private readonly HttpClient client;

public A() {
    var serviceProvider = new ServiceCollection()
        .AddHttpClient("YourHttpClientName")
        .Configure<HttpClientFactoryOptions>("YourHttpClientName", options =>
            options.HttpMessageHandlerBuilderActions.Add(builder =>
                builder.PrimaryHandler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (m, crt, chn, e) => true
                }))
        .BuildServiceProvider();
    var _httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
    client = _httpClientFactory.CreateClient();  //HttpClient instance created
    //TODO: Add custom message handler without DI.
}

我刚刚检查了 ConfigurePrimaryHttpMessageHandler 的实现并将其链接到您的设置中。


我的建议是更改您的代码并正确使用 DI,因为 .NET Core 严重依赖于此。

关于c# - .NET 核心 : HttpClientFactory: How to configure ConfigurePrimaryHttpMessageHandler without dependency injection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63879068/

相关文章:

c# - 如何使用户控件的背景透明?

azure - 在 Azure 中作为 Docker Linux 托管的 .NET CORE 2.1 应用程序中获取远程 IP 地址

.net-core - Entity Framework Core 无法使用子对象和 GUID 创建种子

c# - .NET Core - Selenium RemoteWebDriver - PlatformNotSupportedException

javascript - 用于平滑立方体尺寸增加的循环

c# - MVC 4 - 包含两个模型的详细信息页面

c# - 如何在一个 Controller 中使用 .net Core 创建几个 url

c# - 将 DbSet<TEntity> 属性移动到 Entity Framework Core 中的单独类

c# - 是否可以在 net core 中加载特定于平台的 .net 库?

c# - 为什么在除法(/)之前执行方法调用(即ToString)?