是否可以创建多个端点,这些端点将使用自己的用户名/密码进行身份验证? (每个端点都有自己的凭据)
我有一个端点的示例,工作正常。我不知道如何使用相同的身份验证方法添加多个端点。
我的例子:
String adress1 = "http://localhost/CalculatorService";
String adress2 = "http://localhost/CalculatorService/en1/";
Uri[] baseAddresses = { new Uri(adress1) };
ServiceHost host = new ServiceHost(typeof(CalculatorService), baseAddresses);
ContractDescription contDesc = ContractDescription.GetContract(typeof(ICalculator));
ServiceCredentials cd = new ServiceCredentials();
cd.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
cd.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator();
BasicHttpBinding b1 = new BasicHttpBinding();
b1.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
b1.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.HttpGetUrl = new Uri(adress1);
host.Description.Behaviors.Add(cd);
host.Description.Behaviors.Add(smb);
EndpointAddress adr1 = new EndpointAddress(baseAddresses[0]);
ServiceEndpoint en1 = new ServiceEndpoint(contDesc);
en1.Binding = b1;
en1.Address = adr1;
en1.Name = "en1";
ServiceEndpoint en2 = new ServiceEndpoint(contDesc);
en2.Binding = new BasicHttpBinding();
en2.Address = new EndpointAddress(adress2);
en2.Name = "en2";
host.AddServiceEndpoint(en1);
host.AddServiceEndpoint(en2);
host.Open();
身份验证类:
class CustomUserNameValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (userName.ToLower() != "test" || password.ToLower() != "test")
{
throw new SecurityTokenException("Unknown Username or Incorrect Password");
}
}
}
接口/类:
[ServiceContract]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
return n1 + n2;
}
public double Subtract(double n1, double n2)
{
return n1 - n2;
}
public double Multiply(double n1, double n2)
{
return n1 * n2;
}
public double Divide(double n1, double n2)
{
return n1 / n2;
}
}