MVC 4 ApiController Session access

Nothing is accidental when it comes to the behavior of Microsoft technology. It was a conscious decision to not provide access to session state from the ApiController in the same manner as the Controller class. I assume this was an attempt to appear more RESTful in the eyes of the development community by being stateless. Yes, the session is not easily available but with a quick look at an ApiController request, the session cookie is being transferred:

There are many solutions to extending the ApiController to have access to session state and this post illustrates one for MVC version 4.

Starting with the basic template, the WebApiConfig class located in the App_Start folder can be easily change to extend the routing handler to have access to session.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Routing;
namespace MySample.Web
    public static class WebApiConfig
        public static void Register(HttpConfiguration config)
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            ).RouteHandler = new SessionRouteHandler();            
        public class SessionRouteHandler : System.Web.Routing.IRouteHandler
            System.Web.IHttpHandler System.Web.Routing.IRouteHandler.GetHttpHandler(System.Web.Routing.RequestContext requestContext)
                return new SessionControllerHandler(requestContext.RouteData);
        public class SessionControllerHandler : System.Web.Http.WebHost.HttpControllerHandler, System.Web.SessionState.IRequiresSessionState
            public SessionControllerHandler(System.Web.Routing.RouteData routeData)
                : base(routeData)
            { }

The session can then be referenced in the ApiController using HttpContext.Current.Session.

So why not plumb it in by default?  Yes, session should be used sparingly in order to maximize scalibility but one of the benefits of using MVC is its rich framework.  Good design is using the available resources and technology as effective as possible.

This entry was posted in ASP.Net, C#, MVC. Bookmark the permalink.

4 Responses to MVC 4 ApiController Session access

  1. says:

    I’ɗ like to find out more? I’d care to find ouut more detɑils.

  2. ahmed says:

    but simple question
    what is the difference between RouteTable.Routes.MapHttpRoute
    and config.Routes.MapHttpRoute
    which is the default when creating the MVC Project

  3. Quoc.Nguyen says:

    Good. I tried, and it work fine. Thank you

  4. Leon says:

    Good article!!! Hope to see more articles.

Leave a Reply

Your email address will not be published. Required fields are marked *