如何配置使用连接服务创建的 WSDL 客户端以使用基本身份验证?

How can I configure a WSDL client created with Connected Services to use Basic Authentication?

我有一个第 3 方 WSDL 服务,我需要将其集成到 .NET Core 2.1 webapp 中。

我通过 "Add Connected Service" > "Microsoft WCF Web Service Reference Provider" 添加了服务。

我有一些实用程序 class 可以像这样配置服务:

ServiceClient servicePort = new ServiceClient(); 

servicePort.ClientCredentials.UserName.UserName = USERNAME;
servicePort.ClientCredentials.UserName.Password = PASSWORD;

setupHttpHeader(servicePort.InnerChannel );

其中

    public static void setupHttpHeader( IClientChannel serviceChannel )
    {
        using (new OperationContextScope( serviceChannel ))
        {
            // Add a HTTP Header to an outgoing request
            HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
            requestMessage.Headers["Authorization"] = "Basic " + System.Convert.ToBase64String(Encoding.UTF8.GetBytes(USERNAME + ":" + PASSWORD));
            OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
        }
    }

现在,当我尝试在我的控制器中调用端点时,我得到了这个异常:

System.ServiceModel.Security.MessageSecurityException: The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'basic realm="appbox object-model"'.     

在用于连接第 3 方服务的旧 .NET Framework 4.0 示例中,有一个 app.config 具有一些绑定配置。他们看起来像这样:

      <security mode="TransportCredentialOnly">
        <transport clientCredentialType="Basic" />
      </security> 

我需要在我的项目中添加什么才能完成这项工作?

this issue comment 中找到了解决方案。

在生成代码的 GetBindingForEndpoint 部分,需要有如下内容:

System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.Transport);
result.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Basic;

在我的例子中,我需要 TransportCredentialOnly,因为端点是 http 而不是 https