.NET Core调用 SOAP(WCF)服务的方法及示例代码

.NET Core中,虽然WCF(Windows Communication Foundation)并不是默认支持的,但我们可以通过一些工具和库来实现对SOAP服务的调用。本文将介绍几种常见的方法,并提供示例代码。

1、.NET Core中使用WCF相关文档

WCF .net core at GitHub

BasicHttpBinding Tests

ClientCredentialType Tests

2、调用示例代码

basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
factory = new ChannelFactory(basicHttpBinding, new EndpointAddress(new Uri("https://someurl.com/ws/TheEndpoint.pub.ws:AService")));
factory.Credentials.UserName.UserName = "usern";
factory.Credentials.UserName.Password = "passw";
serviceProxy = factory.CreateChannel();
((ICommunicationObject)serviceProxy).Open();
var opContext = new OperationContext((IClientChannel)serviceProxy);
var prevOpContext = OperationContext.Current; // 可选的,如果没有办法,这可能已经设置
OperationContext.Current = opContext;
try
{
    var result = await serviceProxy.getSomethingAsync("id").ConfigureAwait(false);
    // cleanup
    factory.Close();
    ((ICommunicationObject)serviceProxy).Close();
}
finally
{
  // *** ENSURE CLEANUP *** \\
  CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
  OperationContext.Current = prevOpContext; // 或者设置为null(如果没有捕获前面的上下文)
}

推荐阅读
cjavapy编程之路首页