tags:

views:

92

answers:

1

Hi everybody, I have a WCF service like this:

[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";
    }
}

How can I write the method login and create the client application? Thanks you.

+1  A: 
[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;
    }
}

You can identify a session by the current Session id. After a user authenticates correctly you can add this session to the list of authenticated session.

Mind: This is just some pseudo code. The session id should removed when the session is cloced, the list I use is not threadsafe,... But I hope this helps you get into the right direction.

Flo
You'll also need to use a binding that supports sessions for this to work. See http://msdn.microsoft.com/en-us/library/ms730879.aspx
Chris O
Thanks you everybody. I have more question: if I have more getmoredata or getsomedata method so I also have to check SessesionID first?
Trần Quốc Bình
Yes. Whenever you want to make sure that the user is logged in, you have to check if the session ID is in the list.
Flo
Ok, I got it. Thanks you again. ^^
Trần Quốc Bình
You're welcome :)
Flo