Use ASP.NET output caching safely with post-back

The venerable ASP.NET output caching mechanism is useful for caching HTML fragments generated by controls. This can have a massive impact on performance and scalability of sites, but the implementation is not without drawbacks. One common problem encountered with web forms is how to use output caching, but disable it for post-back or similar scenarios. This can be important, for example, in presenting paged search results, where it can be advantageous to cache the first page of results but users may less frequently go to the second page.

In order to do this, override the GetVaryByCustomString method in Global.asax as follows:

  /// <summary>
  /// Added to support control output caching, varying by URL. 
  /// </summary>
  public override string GetVaryByCustomString(HttpContext context, string custom)
  {
	  switch (custom.ToUpper())
	  {
		  case "RAWURL":
			  {

				  if (context.Request.RequestType.Equals("POST"))
				  {
					  context.Response.Cache.SetNoServerCaching();

					  return "POST " + DateTime.Now.Ticks + " " + context.Request.RawUrl;
				  }
				  else 
					  return context.Request.RawUrl;
			  }
		  default:
			  return "";
	  }
  }

Then, on any control for which you wish to enable output caching but only if the page load is not a post-back, add the following directive:

<%@outputcache duration=”3600″ varybyparam=”none” varybycustom=”RAWURL” %>

Note that the ‘duration’ value is in seconds, and set it accordingly. Obviously the ‘varybycustom’ value can be set to any value desired, as long as it is trapped appropriately in GetVaryByCustomString().

One can easily combine this approach with one sensitive to different cookies as well (one example). One could similarly key off of page-level variables stored in view state, application state variables, etc.; the name of the variable by which to vary may for example be stuffed, with an appropriate prefix, into ‘varybycustom’ in the directive. Strategies like these can be used to achieve a range of different effects, for instance to use output caching safely with paging.

Leave a comment