简体   繁体   中英

How to remove the “user specific data-cache” once the session(In Proc) gets timeout in ASP.Net?

We are setting session-timeout for 1 hour:

<system.web>  
  <sessionState mode="InProc" timeout="60"/>  
</system.web> 

It works as expected.

Alongwith "Session", we create user specific data-cache to reuse the data.

We use unique cache-key for each logged in user:

var studentId = GetStudentIdFromRequest();
var cacheKey = "SyllabusInfoCacheKey_" + studentId;

We set the expiration time of cache as:

Cache.Insert("MyKey", myObject, null, DateTime.Today.AddDays(1), TimeSpan.Zero);

But I need to remove the user specific data-cache once the session gets timeout.

Kindly help me out.

If you want the data in cache to be in sync with the session, i would suggest to change the approach ie to store the data in session itself instead of cache. Your requirement will be automatically taken care of.

PS: In your previous question i had suggested the Cache approach, since you wanted to use Cache instead of Session. But it looks like the use case, suits best for Session usage instead of Cache. Please comment if you see any issue with the Session approach.

Please try below.


Put below code in Global.asax file in your project.

Shared Dict As New Dictionary(Of String, String)

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs on application startup
    Application.Add("AllSession", Dict)
End Sub

Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs when a session ends. 
    ' Note: The Session_End event is raised only when the sessionstate mode
    ' is set to InProc in the Web.config file. If session mode is set to StateServer 
    ' or SQLServer, the event is not raised.
    If Dict.ContainsKey(Me.Session.SessionID) Then
        HttpRuntime.Cache.Remove(Dict.Item(Me.Session.SessionID))
        Dict.Remove(Me.Session.SessionID)
        Application.Add("AllSession", Dict)
    End If
End Sub


Please put this code in you vb file where you are assigning session.

    Dim cacheKey As New Random
    Dim DictcacheKey As Dictionary(Of String, String)

    DictcacheKey = Application("AllSession")
    If Not DictcacheKey.ContainsKey(HttpContext.Current.Session.SessionID) Then
        DictcacheKey.Add(HttpContext.Current.Session.SessionID, cacheKey.Next())
        Application.Add("AllSession", DictcacheKey)
        Cache.Insert(cacheKey.Next(), DictcacheKey, Nothing, DateTime.Today.AddDays(1), TimeSpan.Zero)
    End If

Note: convert this code in C# if you are not using vb.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM