Thursday, September 4, 2008

How to use Sessions in WCF and Silverlight (basicHttpBinding)

I was writing a WCF Service for a Silverlight application and I needed to use Sessions in my WCF service to store some info. As you know Silverlight 2 (beta 2) only supports basicHttpBinding and therefore we can not use sessions as in wsHttpBinding. I wanted to write something like:

HttpContext.Current.Application.Add("MyKey", someInfo);

But HttpContext.Current returned null. After reading some threads in forums I found this workaround, make your WCF Service ASP.NET compatible:

1. Put this attribute on your WCF Sevice class: [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService

2. In your Web.config for your WCF Service project set:

<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

This will make HttpContext.Current return something and you can now store your sessions. The difference I found in my solutions from some others is that I had a separate project for my WCF service than my ASP.NET web-project and that made the HttpContext fail.

Read more here: