【问题标题】:Dotnetcore: how to get httpClient from a service reference?Dotnetcore:如何从服务引用中获取 httpClient?
【发布时间】:2020-06-02 14:40:10
【问题描述】:

我想我需要弄清楚如何从服务引用中获取 httpclient。

我一直在连接到返回证书错误的 Web 服务。我想绕过那个错误,在 dotnet 框架中,这很简单。但是,在核心中,我被告知我必须获取 httpClient 并向其添加自定义处理程序。没关系,但是当我有一个 Web 服务的服务引用对象时,我不知道如何从中获取 httpClient。

首先,我添加了对 Web 服务(不是我控制的)的服务引用。

接下来,

BasicHttpBinding httpBinding = new BasicHttpBinding();

    httpBinding.Security.Mode = BasicHttpSecurityMode.Transport;

    httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

    httpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Basic;

        SRI_CAP_AlertCollector.AlertCollectorServicePortClient client = new SRI_CAP_AlertCollector.AlertCollectorServicePortClient(httpBinding, endpoint);

但是当我调用其中一种服务方法(异步)时,由于证书而出现错误。 由于这是一个概念验证,我想绕过证书错误。

在 DotNetCore 中,这样做与使用 dotnet 框架不同。所以我试图弄清楚如何从服务引用中获取 httpClientHandler 以便我可以添加一个 ServerCertificateCustomValidationCallback

【问题讨论】:

  • 嘿,Les,没有足够的信息可以离开这里。您能否添加一些代码并解释您要在更大的应用程序上下文中解决什么问题?
  • 见上面添加的措辞。

标签: .net-core service-reference


【解决方案1】:

由于您使用 .net 核心,我建议您使用 HttpClientFactory。理想情况下,您可以在 DI 容器中注册一个命名的客户端工厂,如下所示。

services.AddHttpClient("named_client")
                .ConfigurePrimaryHttpMessageHandler(() =>
                {
                var handler = new HttpClientHandler();

                //Get certificate

                X509Certificate2 cert = null;
                //Load your certificate                

                if (cert == null) throw new IndexOutOfRangeException($"No certificate found");

                handler.ClientCertificates.Add(cert);
                handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

                return handler;
            });

在上面的代码中HttpClientHandler.DangerousAcceptAnyServerCertificateValidator 包装了返回true 的回调函数。 当您在课堂上解决httpfactory 并创建一个新客户端时,您应该这样做

public class ClassResponsibleForHttpCalls
{
    private readonly IHttpClientFactory _clientFactory;

    public ClassResponsibleForHttpCalls(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }
    public async Task Get(int id)
    {
        requestMessage.Content.Headers.ContentType.CharSet = "";
        using var client = _clientFactory.CreateClient("named_client");

        //Use your client...
    }
}

使用您之前设置的同名客户端作为参数。

【讨论】:

  • 我应该为“named_client”添加什么我将在我的服务参考中查找什么名称?
  • 它不工作。仍然获得带有权限错误的 SSL/TLS 安全通道。
  • 我更新了我的答案。 “named_client”只是一个名字。当您从工厂创建客户端时,您应该使用相同的名称。检查我的更新答案
  • 我想我不知道如何使用脚手架服务参考来完成这项工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-22
  • 1970-01-01
  • 2012-02-02
  • 1970-01-01
  • 2020-03-16
  • 1970-01-01
  • 2012-03-15
相关资源
最近更新 更多