Tuesday, May 24, 2011

Enable Session State in a WCF service

The concept of session in a WCF service is widely different from a typical ASP.NET application where the session is initiated and maintained on the server. Sessions in WCF are per call and are created in the context of the channel that received the service request. I will keep this simple. If you need access to Session data in a WCF service there are 2 things that need to happen. In the web.config of your service application, the aspnetcompatibility needs to be enabled like so....
1.
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibiltyEnabled="true"/>

2. Add the following line to the class that implements your service interface like so...

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

The AspNetCompatibilityRequirementsMode enum has three possible values, Allowed NotAllowed and Required. Set the value of this enum according to your needs.

5 comments:

  1. Ran into this just recently! Needed to cache a connection string hash in session state for a WCF data service hosted in IIS. Remember that you are keeping your data in an ASP.NET session object - to retrieve it you must have a reference to the current httpcontext, ala:

    'Get current HTTP Context
    Dim currentHttpContext = HttpContext.Current
    'Return current Reporting DB Connection String Cache
    If Not currentHttpContext.Cache(DB_CACHE_VAR) Is Nothing Then
    Return DirectCast(currentHttpContext.Cache(DB_CACHE_VAR), Dictionary(Of Guid, String))
    Else
    Return Nothing
    End If

    ReplyDelete
  2. And yes, in that example I am using the Cache object rather than Session. In my case, the connection string lookup should be available to all sessions.

    ReplyDelete
  3. Yes, agreed but you can share the same ASP.Net Session state on the server side for subsequent requests. See this
    http://blogs.msdn.com/b/wenlong/archive/2010/02/21/using-asp-net-sessions-from-wcf.aspx

    Is this what you are trying to do?

    ReplyDelete
  4. Can you plz tell me that, is it possible to access the session variables (created in WCF service) in an asp.net application?

    ReplyDelete
  5. That depends on your session management, whether you are using InProc, StateServer or a database. With a little work I think it is possible but have never had a need to do so. Theoretically there are multiple strategies to achieve this goal that I can think of.

    ReplyDelete