为了便使这种方式自由度更高,今天我就把这个服务器端纯代码化了。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.ServiceModel;
- using System.IdentityModel.Selectors;
- using System.ServiceModel.Description;
- namespace wcf.username
- {
- class Program
- {
- static void Main(string[] args)
- {
- EndpointAddress endp = new EndpointAddress("http://localhost/myservice");
- WSHttpBinding ws = new WSHttpBinding();
- ws.Security.Mode = SecurityMode.Message;
- ws.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
- ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
- behavior.HttpGetEnabled = true;
- behavior.HttpGetUrl = new Uri("http://localhost/myservice/mex");
- ServiceHost sh = new ServiceHost(typeof(serverdo), new Uri(endp.ToString()));
- sh.Description.Behaviors.Add(behavior);
- sh.Credentials.ClientCertificate.Authentication.CertificateValidationMode =
- System.ServiceModel.Security.X509CertificateValidationMode.None;
- sh.Credentials.UserNameAuthentication.UserNamePasswordValidationMode =
- System.ServiceModel.Security.UserNamePasswordValidationMode.Custom;
- sh.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new checkUserName();
- sh.Credentials.ServiceCertificate.SetCertificate(
- System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
- System.Security.Cryptography.X509Certificates.StoreName.My,
- System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName, "MyServer");
- sh.AddServiceEndpoint(typeof(Iservice), ws, endp.ToString());
- sh.Open();
- Console.WriteLine("ok");
- Console.Read();
- }
- }
- class checkUserName:UserNamePasswordValidator
- {
- public override void Validate(string userName, string password)
- {
- if (userName != "jac" && password != "jac")
- {
- throw new FaultException("userName and passWord be error");
- }
- }
- }
- [ServiceContract]
- interface Iservice
- {
- [OperationContract]
- string test(string msg);
- }
- class serverdo:Iservice
- {
- #region Iservice 成员
- public string test(string msg)
- {
- Console.WriteLine("user inter:" + msg);
- return "user inter:" + msg;
- }
- #endregion
- }
- }