三种调用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();
        }

猜你喜欢

转载自www.cnblogs.com/TianPing/p/10089739.html