Output Cache With Usercontrol on Masterpage and Multiple VaryByCustom
Hey All,
Had an issue today where I had a masterpage which
was inherited from 2 pages. On the masterpage I had a control which is
using output cache to cache the control. But ran into an issue where
you would visit the first page say Test.aspx and you would see the
control as expected, but then visit Test2.aspx and you get the same
instance of the cached control from the first page. To get around this
I made use of varybycustom in the controls output cache directive.
Firstly in your global.asax add a GetVaryByCustomString override:
Public Overrides
Function GetVaryByCustomString(ByVal context
As System.Web.HttpContext,
ByVal custom As String)
As String
Dim val = String.Empty
Select Case custom.ToUpper()
Case "PAGENAME"
val = context.Request.Path.ToString()
End Select
Return val
End Function
Then modify your output cache directive to make use of this like so:
<%@ OutputCache VaryByCustom="PageName" Duration="86400" %>
As you can see now the control will be varied by a custom string, the
GetVaryByCustom override does this by checking the command argument and
depending on what it is returning a value, in this case we are only
using PageName but in my main app I have many things in here such as
UserID etc etc. Now if you visit page 1 then page 2 you will see you
have 2 seperate instances of the cached control on the pages.
Multiple VaryByCustom:
Another thing I wanted to do was have multiple VaryByCustom
parametres, I decided to just use the same style as the other varyby
strings and seperate the keys with a ;, I then just changed the
GetVaryByCustomString to allow for this, something like this seems to
do the trick:
Public Overrides Function GetVaryByCustomString(ByVal context As System.Web.HttpContext, ByVal custom As String) As String
Dim keys() As String = custom.Split(";"c)
Dim val As String = String.Empty
For Each key As String In keys
Select Case key
Case "PageName"
val &= context.Request.Path.ToString()
Case "UserID"
val &= "1"
Case "CurrentDate"
val &= DateTime.Now.ToString()
End Select
Next
Return val
End Function
Now you can use a VaryByCustom string like so:
<%@ OutputCache Duration="3600" VaryByCustom="UserID;PageName" %>
Hope you find that useful.
Thanks
Stefan