ASP.NET Web API 2 is designed as a stateless Web API framework, therefore, the visitor session context is not automatically created on each web request. Normally, for a Sitecore solution, it is necessary to enable Sitecore Context session-dependent features/data in some or even most of Web API calls context.
One of the options is to create Web API Route which would automatically enable session state for all Web API calls that are made via this route. To be clear, we are basically looking for enabling a regular ASP.NET session state in the context of ASP.NET Web API 2 calls.
The solution option which we consider in this specific case has the following implementation approach:
- Register a new route using ASP.NET Web API 2 – a dedicated route for the session-context-enabled Web API calls handling.
- Retrieve the new route’s object using a regular ASP.NET and enrich it with a request handler that creates a regular ASP.NET session state context.
The set of C# classes:
Enable the Web API Route Registration code execution at Sitecore start-up by the following Sitecore config include file:
With this approach, it is possible to segregate the stateless and the session-context-enabled Web API calls by a specific route (the route path prefix). The session context existence will depend on which Web API route is used to make the Web API Controller Action call.
This may not be an ideal solution when you would like to specify the session context existence as a pre-requisite for a specific Controller Action. In that case, you may rather consider implementing the session state context enablement with an Action Filter attribute, with which you can decorate a Controller Action or even the whole Controller class.