2012-06-29 49 views
0

我開始爲WCF爲我的c#/。net應用程序開發一個REST API。具有詳細返回信息的自定義UserNamePasswordValidator?

我使用自定義的UserNamePasswordValidator進行基本的HTTP身份驗證。它驗證我的API方法。

它基於此示例代碼,我可以讓沒有任何問題的工作:

public class CustomUserNameValidator : UserNamePasswordValidator 
{ 
    public override void Validate(string userName, string password) 
    { 

     if (null == userName || null == password) 
     { 
      throw new ArgumentNullException("You must provide both the username and password to access this service"); 
     } 

     if (!(userName == "user1" && password == "test") && !(userName == "user2" && password == "test")) 
     { 
      throw new FaultException("Unknown Username or Incorrect Password"); 
     } 
    } 
} 

如果驗證失敗,我不能回送什麼,但「401未授權」給客戶端。我知道這是應該的方式,但是在這種情況下,是否有可能以某種方式將一些詳細信息發回給我的呼叫者?一些自定義錯誤消息或一些更詳細的信息。如果不是這樣,我的客戶端只有身份驗證失敗的http信息,在我的情況下是不夠的。

回答

2

也許你應該使用WebFaultException <>,在我來說,我使用的是這樣的:throw new WebFaultException<string>("Bad Request", HttpStatusCode.Unauthorized);

+0

UserNamePasswordValidator是** **驗證可擴展性和不** **授權,但使用HttpStatusCode.Unauthorized仍是正確的[HTTP RFC2616 10.4.2表示](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)401 Unauthorized實際上暗示**身份驗證**。 –

相關問題