Wednesday, April 27, 2016

Using the Session object in ASP.NET Web API

By default when you try to use the Session object inside ASP.NET Web API the Session object will be null. This is not a bug but expected behavior as HTTP is stateless – meaning that there shouldn’t be a need for any kind of server state as every HTTP request should contain all the information needed to process the request.

Sorry to all the HTTP and REST purist, but the reality is messy and sometimes using the session state can be the easiest solution. 

To instantiate the session during your Web API request, you can add the following line to your Application_PostAuthorizeRequest method inside the global.asax:

System.Web.HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);

More information about this method here: https://msdn.microsoft.com/en-us/library/system.web.httpcontext.setsessionstatebehavior(v=vs.110).aspx

No comments: