Is it possible to access HttpContext.Current.Session from Web API
Asked Answered
P

3

29

Is it possible to access HttpContext.Current.Session through a WebAPI ? can we make it inheriting IRequiresSession?

I have a generic handler doing a Session set after an API call which I want to remove.

public void AccountController : ApiController, IRequiresSessionState
{
public void Login()
{
setsession(){}
} 
}
Paraphernalia answered 9/11, 2013 at 23:49 Comment(1)
You will most likely need to setup asp.net to use Forms Authentication, though it may be possible otherwise.Esoterica
L
50

Technically, yes, although I'd really advise against this practice - a REST API should be completely stateless (cookies and other client-side state is OK).

If you absolutely must do this, you can grab the HTTP context like so:

var context = Request.Properties["MS_HttpContext"] as HttpContext;

At which point you just use its Session property to get the session.

Note that this breaks certain contracts assumed by System.Net.Http - specifically it means your API controllers can never be self-hosted because they're coupled to ASP.NET. If you're OK with this, and with the fact that your API controllers may not work properly from a web farm unless you re-architect everything to use distributed sessions - well then, go for it.

P.S. It is also possible to use IRequiresSessionState, but you can't use it on the controller itself, you need to use it on an HttpControllerHandler and set it as the RouteHandler. The approach is discussed in this MSDN thread. Again, I can't recommend strongly enough against this idea, it violates the basic principle of a Web API - but, if you've got a really good reason for it, then it's another option which is a bit more reusable.

Lubra answered 10/11, 2013 at 0:15 Comment(3)
Everyone gives this warning, BUT nearly every webapi that has authorization essentially does the same thing as sessions.... it uses some token to find existing state that says whether they can or can't do something. (things like JWT do things a bit different, but gets a lot of hate from security experts for that )Cheke
Thanks @KeithNicholas, I was about to ask if you have an Auth token / cookie, then how do you grab it without this!Choral
This property is of type HttpContextWrapper not HttpContext.Idealistic
R
18

Casting it as HttpContext did not work for me using Web Api 2.1. However I could use HttpContextWrapper.

var context = Request.Properties["MS_HttpContext"] as HttpContextWrapper;
Rowland answered 13/6, 2014 at 19:32 Comment(0)
W
1

Yes - although not recommended. Here's a working answer based on the answers above (for WebAPI version 2.x)

  var context =(HttpContextWrapper)Request.Properties["MS_HttpContext"];
  var sessionId = context.Request.Params["ASP.NET_SessionId"];
Wolves answered 25/7, 2022 at 5:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.