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
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.
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.
Add
protected void Application_PostAuthorizeRequest()
{
System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
to global.asax
If PostAuthorizeRequest doesn't work, then try BeginRequest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With