Asp.Net Forms Authentication, Cached User Control and Session ID
I faced the following problem that i wanted to share with you, I have a user control that populates a menu to be shown to the user, the menu is populated based on the user privileges. i wanted to cache this user control so that the menu population logic won't run for every page request, so i decided to cache the output of the user control based on the SessionID, to do this i added the following attribute to the control
<%@ OutputCache Duration="1" VaryByCustom="Session" VaryByParam="None" %>
the VaryByCustom attribute allows you to vary the cached output by your defined string, having specifying the "Session" as my defined string i had to override the HttpApplication.GetVaryByCustomString method in the Global.asax file
Overrides Function GetVaryByCustomString(ByVal context As HttpContext, ByVal custom As String) As String
If custom = "Session" Then
Return Session.SessionID
Else
Return ""
End If
End Function
The function simply returns the session id so that the user control is cached for this user session only, until now everything is working perfectly, and the menu user control is cached correctly.
later on i added a Logout LinkButton
Protected Sub lnk_Click(ByVal sender As Object, ByVal e As System.EventArgs)
System.Web.Security.FormsAuthentication.SignOut()
Session.Abandon()
Response.Redirect("~/Admin/default.aspx")
End Sub
The code is supposed to log out the user and cleans the session, i expected that the cached user control to be ignored a new version to show but the user control is still showing the cached version, for some unknown reason the Asp.Net is still returning the same session id although the Session.Abandon method should create a new session object.
after googling a little i found this knowledge base article and this blog entry that describe the problem and the solution, the solution was to explicitly remove the asp.net cookie that stores the session id
Protected Sub lnk_Click(ByVal sender As Object, ByVal e As System.EventArgs)
System.Web.Security.FormsAuthentication.SignOut()
Session.Abandon()
Response.Cookies.Add(New HttpCookie("ASP.NET_SessionId", ""))
Response.Redirect("~/Admin/default.aspx")
End Sub
Hope this helps :)
Comments