2010-05-04 81 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