2010-05-04 107 views
3

我有這樣一個WCF服務:簡單的登錄

[ServiceContract(SessionMode=SessionMode.Required)] 
public interface IService 
{ 
    [OperationContract(IsInitiating = true, IsTerminating = false)] 
    void login(string id); 

    [OperationContract(IsInitiating = false, IsTerminating = false)] 
    string getdata(); 
} 



public class Service : IService 
{ 
    public void login(string hashedid) 
    { 
     if (username != "someusername" || password != "somepassword") 
     { 
      // can not get data 
     } 
     else 
     { 
      // can get data 
     } 
    } 

    public string getdata() 
    { 
     return "these are data"; 
    } 
} 

如何我寫的方法登錄並創建客戶端應用程序? 謝謝。

+0

公共無效的登錄信息(用戶名字符串,字符串密碼){ 如果 (用戶名= 「someusername」 ||密碼= 「somepassword」!) { 拋出新的異常( 「未知的用戶名或密碼」); } 其他 {// 可以得到數據 }} 是這樣行嗎? – hanuman0503 2010-05-04 07:38:47

+2

這對兩個參數來說是正確的,但是當你調用getdata()時,你仍然不知道這個人是否已經早先認證,並且你拋出的異常不會被傳回客戶端。你需要拋出一個FaultException或者將包含IncludeExceptionDetailInFaults = true的ServiceDebugBehavior()添加到你的服務主機行爲中。 – flayn 2010-05-04 10:37:25

回答

7
[ServiceContract(SessionMode=SessionMode.Required)] 
public interface IService 
{ 
    [OperationContract(IsInitiating = true, IsTerminating = false)] 
    void login(string username, string password); 

    [OperationContract(IsInitiating = false, IsTerminating = false)] 
    string getdata(); 
} 



public class Service : IService 
{ 
// todo: make threadsafe! 
    public static List<Guid> authenticated = new List<Guid>(); 

    public void login(string username, string password) 
    { 

     if (username == "correctUsername" || password == "correctPassword") 
     { 
      // user has given correct username/pasword 
      Guid currentSessionId = OperationContext.Current.SessionId; 

     // note: can throw Exception when calling login twice or more, check if item exists first 
      authenticated.Add(currentSessionId); 
     } 


    } 

    public string getdata() 
    { 
     Guid currentSessionId = OperationContext.Current.SessionId; 
     if (List.Contains(currentSessionId) 
     { 
       return "these are data"; 
     } 

     return String.Empty; 
    } 
} 

您可以通過當前會話標識來識別會話。在用戶驗證正確後,您可以將此會話添加到已驗證會話的列表中。

注意:這只是一些僞代碼。當會話被關閉時,會話ID應該被刪除,我使用的列表不是線程安全的,但我希望這可以幫助你進入正確的方向。

+2

您還需要使用支持會話的綁定才能工作。請參閱http://msdn.microsoft.com/en-us/library/ms730879.aspx – 2010-05-04 10:50:20

+0

謝謝大家。我有更多的問題:如果我有更多的getmoredata或getsomedata方法,所以我還必須先檢查SessesionID? – hanuman0503 2010-05-05 09:14:13

+0

是的。每當你想確保用戶登錄時,你必須檢查會話ID是否在列表中。 – flayn 2010-05-05 12:22:42