Click here to Skip to main content
15,907,395 members
Articles / Web Development / ASP.NET

Providing session state in ASP.NET WebAPI

Rate me:
Please Sign up or sign in to vote.
4.27/5 (9 votes)
21 Dec 2012CPOL2 min read 140.1K   19   15
Describes how to ensure session state within the ASP.NET WebAPI.


With help of this trick you can provide session state in you RESTful WebApi services. 

Many of the devs like to use WCF REST, but on my opinion ASP.NET team provided us with mode powerful technology to develop more powerful REST services. Special thanks to them for that.  

I have written this tip at frst time, and I hope people do not find it arrogant, it is certainly not meant to be . 


As far as you probably know, by default, HTTP (and by extension, REST) is stateless – and as a result each HTTP request should carry enough information by itself for its recipient to process it to be in complete harmony with the stateless nature of HTTP. 

In order to provide session support, we will need to create 2 custom components:

IRouteHandler, to replace the default HttpControllerRouteHandler and to tell the ASP.NET pipeline to go to our custom HttpControllerHandler

– customized HttpControllerHandler, which will mark the route as being session enabled and then go back to the Web API execution pipeline. 

Web API routing, is operating on the same underlying ASP.NET RouteCollection, and therefore similar principles apply. ASP.NET has a concept of IRouteHandler which is a property on a System.Web.Routing.Route class and is responsible for processing HTTP requests for a route. By default, all Web API routes use HttpControllerRouteHandler which doesn’t do much, except handing over the HttpContexBase to HttpControllerHandler

Using the code

To enforce session in WebApi we need to use IRequiresSessionState markable attribute which is only need for notifying ASP environment about providing session state on a specific module.

So as a result our self implemented HttpControllerHandler will be looked quite simple: 

public class SessionableControllerHandler : HttpControllerHandler, IRequiresSessionState 
    public SessionableControllerHandler(RouteData routeData)
        : base(routeData)

So know we need only to plug our newly created SessionControllerHandler to routing workflow. To do it we need to implement module which will inherits IRouteHandler interface and in GetHttpHandler method just return new instance of session controller handler.   

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

And last one.

We need in route registration add our route selection, for example: 

    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
).RouteHandler = new SessionStateRouteHandler();  

vual ahhh 

Our code  is done. 

To check the performance capacity of this approach lets do the next :  

public class TestController : ApiController 
 public TestController()
 public string GetFromSession()
   if ((HttpContext.Current.Session["SomeData"] as string) == null)
      HttpContext.Current.Session["SomeData"] = "Hello from session";
   return (HttpContext.Current.Session["SomeData"] as string);

If you debug the code above few times, then you will see, that at first time of invoking GetFromsession method in API controller, we will store some data in Session environment primarily,and all consequent execution of that method, will get this value from session storage and push it back to the wire.   

Maybe my naming convention of classes sounds strange, but it's done only for evaluation purposes. Feel free with your own flavour of naming Smile | <img src=  


No history is available, this is the first version. 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Team Leader Delphi LLC
Ukraine Ukraine
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

PraiseThank you for providing very good clear information and solution. Pin
Member 110233367-Apr-20 4:06
Member 110233367-Apr-20 4:06 
QuestionImplicitly convert error Pin
Tausif Khan16-Aug-18 20:34
Tausif Khan16-Aug-18 20:34 
QuestionAn easier way Pin
Chris_Green22-Apr-15 0:43
Chris_Green22-Apr-15 0:43 
AnswerRe: An easier way Pin
Oleksandr Kulchytskyi22-Apr-15 4:41
professionalOleksandr Kulchytskyi22-Apr-15 4:41 
GeneralMy vote of 5 Pin
csharpbd14-Aug-14 3:27
professionalcsharpbd14-Aug-14 3:27 
Questiona problem Pin
keyHu19-Jul-14 15:45
keyHu19-Jul-14 15:45 
AnswerRe: a problem Pin
Oleksandr Kulchytskyi20-Jul-14 9:00
professionalOleksandr Kulchytskyi20-Jul-14 9:00 
QuestionHi! Is there an updated way to do this? Pin
Jason Roner20-May-14 18:14
Jason Roner20-May-14 18:14 
AnswerRe: Hi! Is there an updated way to do this? Pin
Oleksandr Kulchytskyi20-May-14 20:57
professionalOleksandr Kulchytskyi20-May-14 20:57 
GeneralWell Written Pin
BI Road Warrior19-Apr-14 1:54
BI Road Warrior19-Apr-14 1:54 
GeneralRe: Well Written Pin
Oleksandr Kulchytskyi19-Apr-14 4:11
professionalOleksandr Kulchytskyi19-Apr-14 4:11 
GeneralMy vote of 1 Pin
Donatas Maciunas7-Nov-13 23:29
Donatas Maciunas7-Nov-13 23:29 
GeneralRe: My vote of 1 Pin
amolbk9-Dec-13 22:28
amolbk9-Dec-13 22:28 
QuestionТо что надо ! Pin
intruder17-Feb-13 21:16
intruder17-Feb-13 21:16 
AnswerRe: То что надо ! Pin
Oleksandr Kulchytskyi18-Feb-13 1:57
professionalOleksandr Kulchytskyi18-Feb-13 1:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.