Enabling Session variables in Web API

When trying to access Session variables in Web API, I was seeing the familiar and hated “Object reference not set to an instance of an object”. In fact, the error wasn’t  directed at any variable, it was directed at the Session class itself, HttpContext.Current.Session.

Luckily, I found Oleksandr Kulchytskyi’s article on Code Project, and that saved my bacon, and the rest of breakfast for that matter. It’s very clear, so I recommend following his instructions. I am including my implementation, which used Web API 2, partly because on the Internet, things sometimes disappear, and partly because of a modification I had to make.

I have a class that implements the required interfaces:

using System.Web;
using System.Web.Http.WebHost;
using System.Web.Routing;
using System.Web.SessionState;
namespace Coaster.Controllers {
    public class SessionableControllerHandler : HttpControllerHandler, IRequiresSessionState {
        public SessionableControllerHandler(RouteData routeData)
            : base(routeData) { }
    }

    public class SessionStateRouteHandler : IRouteHandler {
        IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) {
            return new SessionableControllerHandler(requestContext.RouteData);
        }
    }
}

The one change from Oleksandr’s instructions is the RouteConfig.cs file, since I believe I’m using a later version that he was:

        routes.MapRoute(
            name: "PagingApi",
            url: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        ).RouteHandler = new SessionStateRouteHandler();

Here is where I should include the obligatory comment about Web API, RESTful services, and Session variables, but I won’t. Adding Session variable to Web API made the most sense for improving application performance and making users happy. So there.

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: