outputcache based on url

The outputcache page directive is very handy – and I tend to use this where appropriate on my usercontrols (.ascx)

You can optionally vary by querystring parameters.

Something that’s missing from the default options is to vary based on the actual url of the page. I was building a site where a random testimonial was pulled from the database and displayed in a small panel. I wanted this to stay constant on each particular url.

Here’s how to do it…

Add this to your global.asax

    Public Overrides Function GetVaryByCustomString(ByVal context As HttpContext, ByVal custom As String) As String
        Select Case custom.ToLower
            Case "pageurl"
                Return Request.FilePath.ToLower
            Case Else
                Return MyBase.GetVaryByCustomString(context, custom)
        End Select
    End Function

Then on your ascx file add the following to the top

<%@ OutputCache Duration="60" Shared="true" VaryByParam="None" VaryByCustom="pageurl" %>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.