Trap
Trap

Reputation: 45

ASP.CORE Session using a DistributedSqlServerCache

We use a DistributedSqlServerCache to store user session data but I have noticed some unexpected/strange behaviour. So I was wondering how a DistributedSqlServerCache works under the hood to help me understand the behaviour that I am seeing.

When a user arrives at the site, immediately a DB entry is inserted, as seen below in img 1.

img 1

When the user logs out or the session times out, the session data is cleared (replaced with some arbitrary default value) and the ExpiresAtTime is also reset, as seen below in img 2.

img 2

Again, another user arrives at the site, and a new DB entry is inserted, as seen below in img 3.

img 3

But this time, if the application pool is recycled or the IIS is reset, then the below (img 4) is the result in the database:

img 4

It appears that the original session has not been emptied and also a new session is started.

For completeness, here's the code we use in StartUp.cs:

services.AddDistributedSqlServerCache(o =>
{
    o.ConnectionString = "conn_string...";
    o.SchemaName = "dbo";
    o.TableName = "PS_PWD_SESSIONS";
});

services.AddSession();

Unless I’ve got the wrong end of the stick, this doesn’t make sense to me. I would be very grateful for any insight into this behaviour.

Upvotes: 4

Views: 1755

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239420

It's best not to worry about this too much. ASP.NET Core knows what it's doing. I think the behavior you're seeing is a result of session key vs. session id. The session id is tied to the actual physical session, persisted in the database here. However, the cookie that gets sent to the user contains only a session key. This session key is always valid and never expires. The client then always sends back this cookie with the same session key, and ASP.NET Core internally decides whether to restore the previous session or create a new one, based on whether the session has expired, etc.

In other words, the underlying data in the actual database doesn't necessarily reflect existing "sessions", at least from a client perspective. To the client, their session lives forever, but in the database it could be deleted. If there's no active session in the database to correspond with the client's session key, then ASP.NET Core just creates a new one.

Upvotes: 4

Related Questions