Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 434
kevindstanley Avatar asked Feb 24 '14 21:02

kevindstanley


People also ask

Can Web API have session?

But in practice, yes - you may need to access a user's session from a web API. By default this is not possible. Attempting to call HttpContext. Current.

How do I get HttpContext session?

In ASP.NET Core, if we need to access the HttpContext in service, we can do so with the help of IHttpContextAccessor interface and its default implementation of HttpContextAccessor. It's only necessary to add this dependency if we want to access HttpContext in service.


2 Answers

Add

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

to global.asax

like image 124
Dejo Avatar answered Oct 16 '22 16:10

Dejo


If PostAuthorizeRequest doesn't work, then try BeginRequest.

like image 1
deepakjg Avatar answered Oct 16 '22 18:10

deepakjg