Using a property in WCF

I have a Service that I would like to use from my client:

[ServiceContract]
public interface IMyAPI
{
    string UserName { [OperationContract] get; [OperationContract] set; }
    string Password { [OperationContract] get; [OperationContract] set; }

    [OperationContract]
    bool StockQuery(string partNo);
}

public class MyAPI : IMyAPI
{
    public string UserName { get; set; }
    public string Password { get; set; }

    private void CheckSecurity()
    {
        if(this.UserName != "test" && this.Password != "123")
        {
            throw new UnauthorizedAccessException("Unauthorised");
        }
    }

    public bool StockQuery(string partNo)
    {
        this.CheckSecurity();
        if(partNo == "123456")
        {
            return true;
        }
        return false;
    }
}

Then on my client I do:

Testing.MyAPIClient client = new Testing.MyAPIClient();

client.set_UserName("test");
client.set_Password("123");
Console.WriteLine(client.StockQuery("123456"));
Console.ReadLine();

The problem is that when I debug, UserNameand are Passwordnot installed, they are zero

+3
source share
1 answer

By default, WCF will create a new instance of your service to serve each call ( PerCall instancing ), so your property sets will not be remembered.

You need to transfer your security data using a service call StockQuery.

[OperationContract]
bool StockQuery(string partNo,String userName,String password);

public bool StockQuery(string partNo,String userName,String password)
{
    this.CheckSecurity(userName,password);
    if(partNo == "123456")
    {
        return true;
    }
    return false;
}

You can get away from this approach using PerSession instancing , where the same instance will be used to serve each client.

[ServiceContract(SessionMode = SessionMode.Required)]
public interface IMyAPI
{
...
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] 
public class MyAPI : IMyAPI
{
...
}

, , WCF.

+8

All Articles