1

How can you use the Session of the HttpContext inside a Web Api 2 controller?

The Session object is null, and while I've seen various ways of enabling session state in the first version of Web Api for ASP.Net, none of these seem to apply to Web Api 2.

Reference for Web Api 1: Accessing Session Using ASP.NET Web API

I realise this isn't an approach everyone agrees with, but it would be useful to have a state-full API in an application I'm working on.

Community
  • 1
  • 1
TimS
  • 5,922
  • 6
  • 35
  • 55
  • REST should be stateless. Forget about session – T.S. Feb 03 '14 at 23:04
  • 3
    I appreciate that, but I'm not after a REST API. I'm after a workaround so that my API can be state-full and access the Session inside an ApiController which has been set elsewhere in the app. Plenty of workarounds existed until Web Api 2. – TimS Feb 04 '14 at 08:37

1 Answers1

0

You can create a Stateful WebAPI, and you can maintain session as in any other Web Application. The only thing that you need do different is to handshake to identify session.

One example can be generating Session and setting session ID in cookie. Then whenever client communicates Server, it attaches the SessionID cookie. Handling of Session in APIController can be done by creating your own BaseAPIController.

Guanxi
  • 3,103
  • 21
  • 38