Session handling in audience criteria
You can use the built-in Optimizely audience criteria without requiring session state on the server side by manually turning off ASP.NET session states. The audience system can autodetect if the session state was turned off and switches to a cookie-based approach for audience criteria that previously used sessions. You can also customize your storage of users' audience sessions.
RaiseStartSession
If the session is turned on, then the AspNet session start event raises the RaiseStartSession
event. If the session is disabled, then the RaiseStartSession
event is raised by HttpApplication AcquireRequestState
event.
Session State
The session-based audience criterion saves its session state inside a session, cookie, or customized state storage. If the session is enabled and there is no registered custom storage, then it uses an HTTP session object as storage. If the session is disabled and there is no registered custom storage, then it uses an HTTP cookie as storage.
Turn on and off session state
The HTTP session object defaults if the AspNet session state mode is not Off. It can be changed explicitly by setting false the property EnableSession
on the VisitorGroupOptions
options.
Customize state storage
To customize storage, it is needed to implement the IStateStorage
interface and register it.
This sample code shows customized state storage and turns the session state off.
internal class InMemoryStateStorage: IStateStorage {
IDictionary<string, string> _states = new Dictionary<string, string>();
public bool IsAvailable => true;
public object Load(string key) {
_states.TryGetValue(key, out string value);
return value;
}
public void Save(string key, object value) {
_states[key] = (string) value;
}
public void Delete(string key) {
_states.Remove(key);
}
}
and the custom state storage can be registered in IServiceCollection
in the startup, like this:
public class Startup {
public void ConfigureServices(IServiceCollection services) {
services.Add<VisitorGroupOptions>((s) => new VisitorGroupOptions(), ServiceInstanceScope.Singleton);
services.Configure<VisitorGroupOptions> (s => s.EnableSession = EnableSession);
services.Add<IStateStorage>(s => new InMemoryStateStorage(), ServiceInstanceScope.Singleton);
}
}
Updated 7 months ago