ASP.NET Web API 2 – Enable Sitecore Context Session State

How do I bring that big thing back into the context?

How do I bring that big thing back into the context?

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.

The Solution

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:

  1. Register a new route using ASP.NET Web API 2 – a dedicated route for the session-context-enabled Web API calls handling.
  2. 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 Code

The set of C# classes:

Enable the Web API Route Registration code execution at Sitecore start-up by the following Sitecore config include file:

Implementation Notes

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.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>