Using a property in WCF

c#, wcf

Solution

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

You need to pass your security details with your `StockQuery` service call.

[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 might get away with this approach using PerSession instancing, where the same instance will be used to service each client.

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

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

But rather then reinventing the wheel I'd look into using some of the built in WCF security.

Problem

I have an Service which I'd like to use properties 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, when I debug, `UserName` and `Password` are not being set, they're both null

Original source