1. 程式人生 > >三種呼叫WCF服務的程式碼

三種呼叫WCF服務的程式碼

 wsHttpBinding,Massage UserName認證

  static void Main(string[] args)
        {
            //使用服務引用方式生成的Client呼叫服務,使用自動生成的配置檔案 WSHttpBinding_IService
            using (ServiceClient client = new ServiceClient())
            {
                client.ClientCredentials.UserName.UserName = "name"
; client.ClientCredentials.UserName.Password = "123"; string result = client.Hello("SomeOne"); Console.WriteLine(result); } //使用配置方件 WSHttpBinding_IService_1 建立通道呼叫服務 using (ChannelFactory<TAePService_Contracts.IService> ChannelFactory = new
ChannelFactory<TAePService_Contracts.IService>("WSHttpBinding_IService_1")) {           var loginCredentials = ChannelFactory.Endpoint.Behaviors.Find<ClientCredentials>(); loginCredentials.UserName.UserName = "name"; loginCredentials.UserName.Password
= "123"; var proxy = ChannelFactory.CreateChannel(); using (proxy as IDisposable) { var result = proxy.Hello("SomeOne"); Console.WriteLine(result); } } //純程式碼方式建立通道呼叫服務 WSHttpBinding binding = new WSHttpBinding(SecurityMode.Message); binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName; binding.ReceiveTimeout = new TimeSpan(0, 5, 0); EndpointAddress address = new EndpointAddress(new Uri("http://192.168.126.129:12122/"), EndpointIdentity.CreateDnsIdentity("ServiceCA")); using (ChannelFactory<Service_Contracts.IService> channelFactory = new ChannelFactory<Service_Contracts.IService>(binding, address)) { ClientCredentials loginCredentials = channelFactory.Endpoint.Behaviors.Find<ClientCredentials>(); loginCredentials.UserName.UserName = "name"; loginCredentials.UserName.Password = "123"; loginCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None; //不認證服務證書 Service_Contracts.IService proxy = channelFactory.CreateChannel(); proxy = channelFactory.CreateChannel(); using (proxy as IDisposable) { var result = proxy.Hello("SomeOne"); Console.WriteLine(result); } }; Console.ReadKey(); }