Web API does not support native HTTP sessions. And it’s the nature of Web API, but there might be times you need HTTP sessions which resembles your bad design. Because a service framework should not support HTTP sessions as it should be a stateless element. So why do we need sessions in Web API ? I think you should not use sessions in Web API in production; eliminate HTTP sessions completely.
So the answer for the question why do we need sessions in Web API is, just to show how you can enable them. Silly though but you can use this in developing some POC and quick functional demos. Never use sessions in Web API because Web API is designed to be stateless.
First we should implement a ControllerHandler which is capable of handling sessions. In order make our ControllerHandler handle sessions we should implement IRequiresSessionState interface as well. Look at the below code.
The next step is to create a RouteHandler as a wrapper to the ControllerHandler we created, this is because when registering routes in the RouteTable we can pass RouteHandler types not ControllerHandler types. Look at the below code for the custom RouteHandler.
Then finally we have to register our RouteHandler in the RouteTable
In order to make our custom route to be used we need to put it on top of other route registrations.