2017-05-31 68 views
1

我想用用戶名/密碼設置wsHttpBinding。 我遇到的問題是如何設置用戶名/密碼?用用戶名密碼wsHttpBinding

我給自己定的:

binding.Security.Mode = SecurityMode.TransportWithMessageCredential; 
     binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName; 

但是,在爲用戶名/密碼的設置?

WSHttpBinding binding = new WSHttpBinding(); 
    binding.Security.Mode = SecurityMode.TransportWithMessageCredential; 
    binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName; 


    Type contractType = typeof(ITest); 
    Type serviceType = typeof(Test); 
    Uri httpUri = new Uri("http://localhost:8083/Test2"); 
    ServiceHost myServiceHost = new ServiceHost(serviceType, httpUri); 

    ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); 
    smb.HttpGetEnabled = true; 
    myServiceHost.Description.Behaviors.Add(smb); 

    myServiceHost.Open(); 

代碼:

namespace ConsoleApplication1 
{ 
    [ServiceContract] 
    interface ITest 
    { 
    [OperationContract] 
    string Ping(); 
    } 
} 



namespace ConsoleApplication1 
{ 
    class Test : ITest 
    { 
    public string Ping() 
    { 
     return "Pong - it works!"; 
    } 
    } 
} 

回答

1

默認情況下,WCF使用Windows的用戶進行身份驗證。但是你可以插入你自己的自定義驗證器。

您需要創建類的繼承UserNamePasswordValidator,然後告訴WCF使用它:

myServiceHost.Description.Behaviors.Find<ServiceCredentials>().UserNameAuthentication 
.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom; 
myServiceHost.Description.Behaviors.Find<ServiceCredentials>().UserNameAuthentication 
.CustomUserNamePasswordValidator = new MyCustomValidator(); 

又見this exampleofficial MSDN documentation

+0

我必須在代碼之前添加一些東西嗎?我在第一行收到空引用異常。 – FrenkyB

+0

基本上問題是這是null:myServiceHost.Description.Behaviors.Find ()。 – FrenkyB

+1

然後,只需將新的ServiceCredentials行爲添加到myServiceHost.Description.Behaviors –