如何以编程方式将客户端连接到WCF服务?

我正在尝试将应用程序(客户端)连接到公开的WCF服务,但不是通过应用程序配置文件,而是通过代码。


我应该怎么做呢?


开满天机
浏览 579回答 2
2回答

墨色风雨

您必须使用ChannelFactory类。这是一个例子:var myBinding = new BasicHttpBinding();var myEndpoint = new EndpointAddress("http://localhost/myservice");using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint)){&nbsp; &nbsp; IMyService client = null;&nbsp; &nbsp; try&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; client = myChannelFactory.CreateChannel();&nbsp; &nbsp; &nbsp; &nbsp; client.MyServiceOperation();&nbsp; &nbsp; &nbsp; &nbsp; ((ICommunicationObject)client).Close();&nbsp; &nbsp; &nbsp; &nbsp; myChannelFactory.Close();&nbsp; &nbsp; }&nbsp; &nbsp; catch&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; (client as ICommunicationObject)?.Abort();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP