Tuesday, October 31, 2006

ASP.NET Caching - Trick or Treat ?

It's a corporate internet web site which pulls content from database, idea is dynamic content but of course this doesn't change often. I was called to help with designing(!) some page so i used opportunity to learn about web performance, let me blog on what i found some other time.

As usual next thing is to cache page output, but there is a glitch (it is!), the web application also includes content mgmt logic as part of it and hence pages will be called with different querystring param for page previews.

<%@OutputCache Duration="60" VaryByParam="*" %>
is ruled out for two reasons 1 it is going to cache preview page output and 2 cache duration is dynamic. So i had to cache the page output based on querystring and in the code behind

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
If Request.QueryString("noCache") Is Nothing Then
lblTime1.Text = "page cached on " & DateTime.Now.ToString()
Response.Cache.SetExpires(DateTime.Now.AddMinutes(60)) 'The duration will be dynamic
Response.Cache.SetCacheability(HttpCacheability.Server)
Else
lblTime1.Text = "page NOT cached " & DateTime.Now.ToString()
End If
End If
End Sub

If page loads with no querystring (normal user), it will be cached for whatever duration of time it needs to. If page loads from content mgmt logic (which will now include querystring noCache) it won't be cached. When i tested with following querystring, looked like it is working as expected

http://localhost/cacheTest/tst.aspx --page was cached for 60 minutes
http://localhost/cacheTest/tst.aspx?noCache=1&param1=abc --page is NOT cached

Struck with a question what will happen in following case

http://localhost/cacheTest/tst.aspx?param1=abc

Expectation is, it will be cached for 60 mins, since it didn't have noCache query string param. May be it will maintain a cached version for this combination of querstrings. But actually what turned out is different, it was spitting out message "page cached on " as it should, but subsequent page loads fetched me current time instead of first cached time, no idea how this is happening. Need to find out a way to see if this is caching multiple versions every time i load this page.

Happy Halloween.

No comments: