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 (ChannelFactoryChannelFactory = new ChannelFactory ("WSHttpBinding_IService_1")) { var loginCredentials = ChannelFactory.Endpoint.Behaviors.Find (); 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 channelFactory = new ChannelFactory (binding, address)) { ClientCredentials loginCredentials = channelFactory.Endpoint.Behaviors.Find (); 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(); }