我有一个第三方WSDL服务,需要将其集成到.NET Core 2.1 Web应用程序中。
我通过"添加已连接的服务">"Microsoft WCF Web服务参考提供程序"添加了该服务。
我有一些配置服务的实用程序类,如下所示:
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"'.
在旧的.NET Framework 4.0示例中,用于连接第三方服务的app.config
具有一些绑定配置。它们看起来是这样的:
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic" />
</security>
我需要在我的项目中添加什么才能使其工作?
在该问题注释中找到了解决方案。
在生成的代码的GetBindingForEndpoint
部分中,需要类似以下内容:
System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.Transport);
result.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Basic;
在我的情况下,我需要TransportCredentialOnly
,因为端点是http
而不是https
。