【问题标题】:Custom HttpClientHandler using FlurlClient doesn't use ClientCertificate使用 FlurlClient 的自定义 HttpClientHandler 不使用 ClientCertificate
【发布时间】:2017-12-17 01:14:03
【问题描述】:

我需要在我的网络请求中添加一个客户端证书,并尝试以这种方式实现它: Stackoverflow

在这个答案的最后,出现了“FlurlClient 方式”。使用和配置 FlurlClient 而不是全局 FlurlHttp 配置。这个我试过了,还是不行。

我创建了一个新的 .NET Core 控制台应用程序来向您展示问题:

static void Main(string[] args)
{
   /****** NOT WORKING *******/
   try
   {
      IFlurlClient fc1 = new FlurlClient(url)
         .ConfigureClient(c => c.HttpClientFactory = new X509HttpFactory(GetCert()));

      fc1.WithHeader("User-Agent", userAgent)
         .WithHeader("Accept-Language", locale);

      dynamic ret1 = fc1.Url.AppendPathSegments(pathSegments).GetJsonAsync()
         .GetAwaiter().GetResult();
   }
   catch
   {
      // --> Exception: 403 FORBIDDEN
   }


   /****** NOT WORKING *******/
   try
   {
      IFlurlClient fc2 = new FlurlClient(url);

      fc2.Settings.HttpClientFactory = new X509HttpFactory(GetCert());

      fc2.WithHeader("User-Agent", userAgent)
         .WithHeader("Accept-Language", locale);

      dynamic ret2 = fc2.Url.AppendPathSegments(pathSegments).GetJsonAsync()
         .GetAwaiter().GetResult();
   }
   catch
   {
      // --> Exception: 403 FORBIDDEN
   }


   /****** WORKING *******/
   FlurlHttp.Configure(c =>
   {
      c.HttpClientFactory = new X509HttpFactory(GetCert());
   });

   dynamic ret = url.AppendPathSegments(pathSegments).GetJsonAsync()
      .GetAwaiter().GetResult();
   // --> OK
}

X509HttpFactory 是从链接的 StackOverflow 答案中复制而来的(但使用 HttpClientHandler 而不是 WebRequestHandler):

public class X509HttpFactory : DefaultHttpClientFactory
{
   private readonly X509Certificate2 _cert;

   public X509HttpFactory(X509Certificate2 cert)
   {
      _cert = cert;
   }

   public override HttpMessageHandler CreateMessageHandler()
   {
      var handler = new HttpClientHandler();
      handler.ClientCertificates.Add(_cert);
      return handler;
   }
}

所以使用全局 FlurlHttp 配置是有效的,而配置 FlurlClient 是无效的。为什么?

【问题讨论】:

  • 你能贴出GetCert()的代码吗?

标签: c# .net-core client-certificates x509certificate2 flurl


【解决方案1】:

这一切都归结为您调用事物的顺序:

  • fc.Url 返回一个 Url 对象,这只不过是一个字符串构建的东西。它不保留对FlurlClient 的引用。 (这允许 Flurl 作为独立于 Flurl.Http 的 URL 构建库存在。)
  • Url.AppendPathSegments 返回“这个”Url
  • Url.GetJsonAsync 是一种扩展方法,它首先创建一个FlurlClient,然后将它与当前的Url 一起使用来进行HTTP 调用。

如您所见,您在该流程的第 1 步中丢失了对 fc 的引用。 2 种可能的解决方案:

1.先构建 URL,然后流畅地添加 HTTP 位:

url
    .AppendPathSegments(...)
    .ConfigureClient(...)
    .WithHeaders(...)
    .GetJsonAsync();

2。或者,如果您想重用 FlurlClient,请使用 WithClient 将其“附加”到 URL:

var fc = new FlurlClient()
    .ConfigureClient(...)
    .WithHeaders(...);

url
    .AppendPathSegments(...)
    .WithClient(fc)
    .GetJsonAsync();

【讨论】:

    猜你喜欢
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2021-06-06
    • 1970-01-01
    • 2019-11-21
    相关资源
    最近更新 更多