How To Prevent the Page from using its Output Cache Based On Some Condition

Some times you may have a page with output cache enabled , and for some reason you don't want to use its output cache ,

Take this seanrio:

you have a page that displays a Dynamic data , and you have 2 users

  1. Viewers: they just View your page.
  2. Editors: they need to Edit the data in the page , and they must see the latest changes they did .

and you decided to Enable output Caching on the page to enhance the Performance  ,

Now the problem is : the Editors can't Edit and See the Latest chages they did , because the page output is cached ,

you need to enforce the page to show and render the latest data without using its current cached output,and without affecting the current cached output.

The solution :

you need to use HttpCachePolicy.AddValidationCallback Method , so that you can register an output Cache  validation Callback ,

Set the Output Caching for your page By setting the output cache in ASPX code as  follows:

  <%@ OutputCache VaryByParam="none" Duration="600" %>

and in Code behind : 

Page_Load:

    Public Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

        If HttpContext.Current.User.Identity.IsAuthenticated Then
            Response.Cache.AddValidationCallback(New HttpCacheValidateHandler(AddressOf ValidateCache), Nothing)
        End If

    End Sub


And the ValidateCache method:

 

    '' this method will invoked every time the page requested

    Public Shared Sub ValidateCache(ByVal Currentcontext As HttpContext, ByVal data As Object, ByRef status As HttpValidationStatus)

        If Currentcontext.User.IsInRole("Editors") Then
            ' Dont use the output cache for the Editors
            ' and force the page to Excute ( handled as a cache miss)
            status = HttpValidationStatus.IgnoreThisRequest

        Else
            ' nothing needed , just use the Output cache
            ' also if you want to Invalidate the page Output cache ,
            ' you need to set the status value to  HttpValidationStatus.Invalid
        End If
    End Sub


How to Test :

Add a break point on the Page_laod event Handler, Page_Load will not called for Non Editors Users (Unless the output Cache Expired ) 


Hope it Helps. 

Anas Ghanem

3 Comments

Comments have been disabled for this content.