Episerver driven MVC Temp Data in Digital Experience Cloud
Our solutions are expected to work in a stateless environment where session affinity (sticky sessions) is disabled. ASP.NET MVC, which is the .NET web foundation of most Episerver projects, are considered stateless with a few exceptions. One of them is their persistence of temporary data across requests.
Getting management of temporary data in a distributed setup is fairly simple. There are plenty of 3rd party solutions based on well-known engines such as Redis that easily can do the job. We are usually basing our state management on Harbour.RedisTempData in a distributed setup that are physically hosted.
The intent with this blog post is not to detail how Harbour.RedisTempData is installed and configured. Instead, I want to cover what you can do when you realize that Digital Experience Cloud doesn’t officially support Redis.
An alternative way of persisting state
It is possible to optimize MVCs management of temporary data by implementing a custom provider using Episerver Dynamic Data Store as temp data state server.
It’s a fairly simple task and actually does the job pretty well. We are using this in projects where it is not possible to rely on 3rd party dependencies such as Redis.
Doing a custom ITempDataProvider only requires you to implementat a fairly simple signature.
It is basically just methods responsible of reading and writing (temp) data based on the context of your controller execution. We of course want to rely on Episervers Dynamic Data Store for these operations.
We are, when both Save and Load are requested, relying on an important method resolving the identity of the current user. It’s falling back on ASP.NET’s Anonymous Identitifaction Module in case the user aren’t authenticated. Be aware that the implementation I show above relies on two important assumptions that may be different in your implementation:
- ASP.NET Membership is used for getting the current authenticated membership
- The active MembershipProvider generated a MembershipProviderKey that is either a integer or a Guid
It is important to be aware of this detail. An example that requires changes is the out-of-the-box WindowsMembershipProvider who relies on a byte-array as MembershipProviderKey. Besides these details, the implementation is pretty self explanatory and simply persists and loads the provided data via the Dynamic Data Store APIs in Episerver.
It is important to register the new TempDataProvider in order to make ASP.NET MVC aware of our implementation.
I would like to emphasize that above example has been taken out of a greater context and are, in reality, recommended to be combined with a more robust way of resolving the user identity. Above example though serves it’s purpose by acting as inspiration for your next TempDataProvider.