WCF sessions with a wsHttpBinding and without windows security

You can have WCF hold session information in memory in a pretty simple way. To eliminate any possible external influences in my instructions, I’ll assume you’re starting with a brand new project:

  1. Create a new WCF Service Library project. This project will already contain a service with a WSHttpBiding binding preconfigured.
  2. Go to the service contract (IService1.cs) and change the ServiceContract attribute to the following:

    [ServiceContract(SessionMode = SessionMode.Required)]
    
  3. Go to the service implimentation (Service1.cs) and add the following ServiceBehavior attribute to the service class (Service1):

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Single)]
    
  4. Add session data as members of the service class (Service1):

    public class Service1 : IService1
    {
        ...
    
        private string UserFullName { get; set; }
    
        ...
    }
    
  5. Use the members to present session specific data (remember to also add them to the service contract, IService1):

    public class Service1 : IService1
    {
        ...
    
        public string Welcome(string fullName)
        {
            UserFullName = fullName ?? "Guest";
            return string.Format("Welcome back, {0}!", UserFullName);
        }
    
        public string Goodbye()
        {
            return string.Format("Come back soon, {0}!", UserFullName ?? "Guest");
        }
    
        ...
    }
    

SessionMode.Required ensures that your clients are session-tracked.
InstanceContextMode.PerSession ensures that an instance of your service class (Service1) is created for every session, so that you can retain session data in it and it will exist in memory across multiple calls in the same session.
ConcurrencyMode.Single ensures that only one thread can enter each service class instance (Service1), and prevents possible concurrency issues if you only access data from the service class (and external thread-safe locations).

EDIT: By default, WSHttpBinding only allows security sessions. But it also support reliable sessions, which allow establishing sessions without security enabled. The following binding configuration disables security and enables reliable sessions:

<wsHttpBinding>
    <binding name="wsHttpBindingConfiguration">
        <security mode="None" />
        <reliableSession enabled="true" />
    </binding>
</wsHttpBinding>

Leave a Comment