Search code examples
asp.netsessionredisazure-redis-cache

Azure Redis - how to simulate session_end event in ASP.NET app when mode=Custom?


The organisation I am working with uses Azure Redis to store session information for its ASP.NET site, which is new ground for me (no experience in this whatsoever).

I need to fire some code when a session ends (either times out, is abandoned etc) and I read that if you have session state saved InProc Session_End will fire, but our org uses the Custom setting for session state. Like this:

<sessionState mode="InProc" customProvider="RedisSessionStateStore" stateConnectionString="tcpip=xxxx" sqlConnectionString="xxxx" cookieless="false" timeout="1000">
      <providers> 
        <add name="RedisSessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" connectionString="xxx" applicationName="xxxx" retryTimeoutInMilliseconds="1000" ssl="false" />
      </providers>
</sessionState>

It's my understanding that the Session_End event won't fire in this case. Other than doing some sort of scheduled job trying to find all the abandoned sessions, is there any way I can capture Session_End event?


Solution

  • Your sessions would be expiring whenever the redis key storing the session data expires (or is evicted) from your redis cache. So you could subscribe to key expiry events from your redis cache using the redis key space notifications feature.

    Documentation: http://redis.io/topics/notifications

    You have to first enable key space notifications on your cache, in Azure, as they are not enabled by default.

    Documentation: https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-configure#keyspace-notifications-advanced-settings