在哪里为测试和实时配置 HttpClient

Where to Configure HttpClient for Both Tests and Live

这听起来像是一个非常基本和常见的问题,但我找不到明确的答案并且我尝试了各种方法。我正在使用 ASP.NET 核心。我想配置 HttpClient,其中包括将 SslProtocol 设置为 Tls12。

这行不通,因为 services.AddHttpClient 需要 class 通过注入获取 HttpClient。

public class BluePayHttpClient : HttpClient
{
    public BluePayHttpClient() : base(new HttpClientHandler()
    {
        AllowAutoRedirect = false,
        CheckCertificateRevocationList = true,
        SslProtocols = System.Security.Authentication.SslProtocols.Tls12
    })
    { }
}

如果我通过注入获取 HttpClient... 那么我将无法在此处设置这些设置!因为 HttpClientHandler 必须在 HttpClient 的构造函数中设置。

然后我可以在启动中设置这些设置,但是

  1. 连接逻辑、协议、基地址和类似的东西是特定模块的一部分,我更愿意将它们放在一起。

  2. 如果我在 Startup 中设置它,那么它没有被配置为集成测试!我需要复制配置代码,重复是不好的。

最好的设置方法是什么?

如果我没有在 BluePayHttpClient 中配置这些基本选项,那么 class 真的没有做太多......我应该直接将 HttpClient 注入 class在使用它吗? services.AddHttpClient<IPaymentProcessor, PaymentProcessor>确实觉得有点别扭。

should I instead inject the HttpClient directly into the classes using it?

是的。

可以注册类型化的客户端,也可以为该类型显式配置

services
    .AddHttpClient<IPaymentProcessor, PaymentProcessor>(c => {
        c.BaseAddress = new Uri("http://localhost:5000");
        //other client configuration here.
    })
    .ConfigurePrimaryHttpMessageHandler(() => {
        //configure handler
        return new HttpClientHandler() {
            AllowAutoRedirect = false,
            CheckCertificateRevocationList = true,
            SslProtocols = System.Security.Authentication.SslProtocols.Tls12
        };
    });

引用Make HTTP requests using IHttpClientFactory in ASP.NET Core

配置也可以在它们的特定模块中完成,并通过启动时调用的扩展方法公开。

阅读Integration tests in ASP.NET Core后有一个更好的方法(您可能需要仔细阅读)

使用 Microsoft.AspNetCore.Mvc.Testing 包可以构建依赖注入容器,从而测试服务配置链,就像您 运行 在线一样。

好处:

  • 无需复制 HttpClient 配置代码。
  • 它测试整个 DI 容器配置。
  • 它允许测试网页和控制器;或测试常规 classes.

缺点:

  • 通用 class 库测试项目必须链接到 front-end Web 项目才能读取配置,即使它被多个项目使用也是如此。
  • Class库测试项目不能在其他web项目中使用。

总的来说...这似乎是一个很好的解决方案。