kevindstanley
kevindstanley

Reputation: 282

Web Api 2 Session

I cannot get session data from while in web api 2. I have verified that the cookie is sending in fiddler.

I know that web api 2 best practice is to be stateless, but due to requirements on a project it is now necessary to be state-full.

I have tried this link. WebAPI 2 attribute routing enable session state

var session = SessionStateUtility.GetHttpSessionStateFromContext(HttpContext.Current)

With the above solution I am getting a null exception on that function.

I also tried replicating the way of doing this the way you would in the old web api by modifying the requesthandler from the route, but that is not available in web api 2.

I currently set some session variables in mvc5. This works and the session stays, but anytime I am trying to use session while in web api 2 the below is null.

HttpContext.Current.Session

Upvotes: 18

Views: 23469

Answers (2)

deepakjg
deepakjg

Reputation: 11

If PostAuthorizeRequest doesn't work, then try BeginRequest.

Upvotes: 1

Dejo
Dejo

Reputation: 2148

Add

protected void Application_PostAuthorizeRequest() 
{
    System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}

to global.asax

Upvotes: 53

Related Questions