Using ASP.NET Session with Silverlight and WCF Services

ASP.NET Session can be easily configured to be used with a WCF service in order to cache user-specific items and avoid repeated round-trips to your database. Here is how.

I've seen a lot of forum posts where users complain that they want to avoid repeated round trips to the database whenever a particular Silverlight Page is requested or if the browser back button has been pressed. Some people want to use Isolated Storage on the client in order to store frequently requested data. However, there is an easier and perhaps more performant way to handlle this: Enable your WCF Service for ASP.NET Session and store the data in Session on the server.

The first thing to do is check your web.config and see if the WCF Service you have added to your web project has Session enabled. You need to have the following element just after the closing </bindings> element tag and just before the opening <services> tag:

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />


Your Service contract class also must have the proper decorations:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceContract]
public class Service1
{

That is pretty much all you need to do. The logic you would use in your Service methods is pretty much like this:

List<MyData> myData = null;

if(HttpContext.Current.Session["WhatIWant"] == null)

{

// get the data from the database (or entity framework model)

HttpContext.Current.Session["WhatIWant"] = myData;

}

else

{

myData = HttpContext.Current.Session["WhatIWant"] as myDataType;

}

return myData;

In order to illustrate this very simply, I created an Entity Framework model consisting of the Northwind Employees table (minus a few unneccessary fields like "Photo") and a WCF method to GetEmployees:

[OperationContract]
public List<Employee > GetEmployees ()
{
List<Employee> emps2 = null;
if (HttpContext.Current.Session["emps"] == null)
{
using (NORTHWINDEntities context = new NORTHWINDEntities())
{
emps2 = context.Employees.ToList();


HttpContext.Current.Session["emps"] = emps2;
Employee e = new Employee();
e.FirstName = "AASESSION";
e.LastName = "AASESSION";
e.Address = "FROM SESSION";
emps2.Add(e);
}
}
else
{
emps2 = (List<Employee>) HttpContext.Current.Session["emps"];

emps2 = emps2.OrderBy(x => x.LastName).ToList();
}

return emps2;
}

Note that in the first block, where the session item is null, I add a "fake" employee with some fields set to "SESSION" so that when the page is refreshed you have proof that the data did indeed come from a Session object rather than from a fresh call to the database.

I also added a generic GetSessionItem method:

[OperationContract]
public object GetSessionItem(string key)
{
return HttpContext.Current.Session[key];
}

In the Silverlight client, I simply exercise the Service client method and populate a DataGrid as a proof of concept.

The first time around, you will see a grid of Northwind Employees. But the second and subsequent page refreshes will show that the data came from Session:

I've sprayed the new row with some red paint, just to make it more noticeable.

The downloadable Visual Studio 2010 Silverlight 4 solution has everything you need (except for the trusty old Northwind Database). This is an IIS web. If you want to run it in the WebDev server you'll need to change the configuration and update the service reference in the Silverlight project to match.

By Peter Bromberg   Popularity  (6718 Views)