Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I recycle ASP.NET sessions stored in SQL Server?

Tags:

asp.net

So we've just started using ASP.NET sessions stored in SQL server - they're pretty neat. However, since sessions now last across an application pool recycle this could pose us a problem if we deploy new code. Is there a way (outside of re-starting the SQL server) to force all sessions (or at least all sessions for an application pool) to be abandoned in this model?

like image 429
John Christensen Avatar asked Jan 10 '12 15:01

John Christensen


People also ask

How do you delete a session in SQL?

You can also remove a session using "Object Explorer" by expanding the "Management" node, then "Extended Events", then "Sessions". You can then right click on the event you want to remove and select "Delete" to drop the session as shown below.

In which database SQLServer session will be stored?

The session state is stored in the ASPState database. The advantage of this method is that the data is persisted even if you restart the SQL server. Custom storage: Both the session state data and the stored procedures are stored in a custom database.

Where does ASP.NET store SessionID?

By default, SessionID values are stored in a cookie. However, you can also configure the application to store SessionID values in the URL for a "cookieless" session.


1 Answers

Add this as a stored procedure in the ASPState database:

        CREATE PROCEDURE [dbo].[DeleteExpiredSessions]
    AS
        DECLARE @now datetime
        SET @now = GETUTCDATE()

        DELETE [ASPState].dbo.ASPStateTempSessions
        WHERE Expires < @now

        RETURN 0

Then add a job to the SQL Server Agent that runs at a regular interval (mine runs at midnight) that executes the following step on that database:

dbo.DeleteExpiredSessions

That makes sure when the sessions expire, they go away even if the process that created them is not around. If you want to get rid of them all on a restart of your process, just execute a:

DELETE [ASPState].dbo.ASPStatsTempSessions

That will remove all sessions in the database.

like image 124
Robert Beaubien Avatar answered Sep 27 '22 23:09

Robert Beaubien