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(){}
} 
}
Kara
  • 6,115
  • 16
  • 50
  • 57
Kubi
  • 2,139
  • 6
  • 35
  • 62
  • You will most likely need to setup asp.net to use Forms Authentication, though it may be possible otherwise. – Chris O Nov 09 '13 at 23:53

3 Answers3

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.

Aaronaught
  • 120,909
  • 25
  • 266
  • 342
  • 4
    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 ) – Keith Nicholas Oct 09 '17 at 02:07
  • Thanks @KeithNicholas, I was about to ask if you have an Auth token / cookie, then how do you grab it without this! – MyDaftQuestions May 04 '18 at 13:40
  • This property is of type `HttpContextWrapper` not `HttpContext`. – Vertigo Jun 19 '23 at 12:30
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;
Nico
  • 1,094
  • 13
  • 17
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"];
MC9000
  • 2,076
  • 7
  • 45
  • 80