ASP.NET FAQ - Output Caching

What is Output Caching?

Output caching lets you cache the output of static aspx pages or portions of pages to improve performance. Since the pages are cached asp.net doesn’t have to regenerate the html for every request.

For more information see:

Permalink
Is there a way that I can clear/expire a page cache from another page/class?

No, not easily unless you use the output cache APIs on Response.Cache and take advantage of the Response.AddCacheDependency() to make the page dependent on a common key.

Then, from the other page or class you could invalidate the common key which would enforce a dependency eviction (since the key page1 depended on changed).
Refer How to remove OutputCache by param?

Permalink
Why do I get the error message ‘Exception Details: System.Web.HttpException: Cache is not available ‘

Try using ‘HttpContext.Current.Cache’ instead of just ‘Cache’ in your code. The compiler probably wasn’t able to resolve the Cache type.

Permalink
How can I cache the page by the complete querystring

Try the following:

<%@ OutputCache Duration='10' VaryByParam='*' %>

This should result in any changes to querystring parameters causing a new version of the page to be cached. Keep in mind that this can significantly increase the amount of memory used for caching, depending on how many querystring parameters you’re using.
Note: ‘*’ is not recommended – it is best to use a list of params that your page truly varies by.

Permalink
Is there any way to cache by browser a page or User Control

Try VaryByCustom=’browser’ in the user control/page.

Permalink
How can I remove the cache of a page (cached with VaryByParam) for certain request params in code

You can attach a cache dependency to the response that is unique per query param, then invalidate the dependency for that particular param:

// add cache item dependency on response 
string cacheKey = 'xxx.aspx?' + queryParam; 
Cache[cacheKey] = new object(); 
Response.AddCacheItemDependency(cacheKey); 

// invalidate the dependency 
string cacheKey = 'xxx.aspx?' + queryParam; 
Cache.Remove(cacheKey);
Permalink
How can I set a page/control to be cached only for certain parameters

Let’s say you set your output cache directive as follows:

<%@ OutputCache Duration='86400' VaryByParam='RegionID' VaryByCustom='ProductID' %>

VaryByCustom – is a string that your application has to interpret in the GetVaryByCustomString override in the gloabal.asax file.

Now, to avoid caching pages for certain ProductIDs you can set the cacheability to private or nocache from your page load for those pages as follows:

VB.NET

Response.Cache.SetCacheability(HttpCacheability.Private)

C#

Response.Cache.SetCacheability(HttpCacheability.Private) ;
Permalink
Is it possible to cache a page by Browser Version and/or some params

Yes. In your page:

<%@ OutputCache Duration='60' VaryByParams='abc;xyz' VaryByCustom='browsermajorversion' %>

In your global.asax file:

VB.NET

Public Overrides Function GetVaryByCustomString(context As HttpContext, custom As String) As String
	If custom.ToLower() = 'browsermajorversion' Then
		Dim browser As HttpBrowserCapabilities = context.Request.Browser
			Return browser.Browser + ' ' + browser.MajorVersion
	Else
		Return MyBase.GetVaryByCustomString(context, custom)
	End If
End Function ’GetVaryByCustomString

C#

public override string GetVaryByCustomString(HttpContext context, string custom)
{ 
	if (custom.ToLower() == 'browsermajorversion') { 
		HttpBrowserCapabilities browser = context.Request.Browser; 
		return browser.Browser + ' ' + browser.MajorVersion; 
	} 
	else 
	{ 
	return base.GetVaryByCustomString(context, custom); 
	} 
}
Permalink
I want to Cache based on HTTP header .How can I do that
<%@OutputCache ... VaryByHeader='UserAgent' %>

or

<%@ OutputCache ... VaryByHeader='Accept-Language' %>
Permalink
How to prevent client Cache? I want every client request get sent to the server even if it’s behind a proxy server and for any browser setting.

You can use tag

<%@ OutputCache Duration='0' Location='None' VaryByParam='none' %>

or

VB.NET

Response.Cache.SetCacheability(HttpCacheability.NoCache)

C#

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Permalink
How to make a page expire immediately in such a way that a warning message ‘This page has expired.’appears

Try the following:

<%@ OutputCache location='none' %>
Permalink
How to remove Output Cache by param

You can attach a cache dependency to the response that is unique per query param, then invalidate the dependency for the particular param:

VB.NET

’add cache item dependency on response 
Dim cacheKey As String = 'webform1.aspx?' + queryParam
Cache(cacheKey) = New Object() ’
Response.AddCacheItemDependency(cacheKey)

’ invalidate the dependency 
Dim cacheKey As String = 'webform1.aspx?' + queryParam
Cache.Remove(cacheKey)

C#

// add cache item dependency on response 
string cacheKey = 'webform1.aspx?' + queryParam; 
Cache[cacheKey] = new object(); 
Response.AddCacheItemDependency(cacheKey); 

// invalidate the dependency 
string cacheKey = 'webform1.aspx?' + queryParam; 
Cache.Remove(cacheKey);
Permalink
How to remove the Cache starting with ‘cachedata_’

VB.NET

Dim enumerator As IDictionaryEnumerator = Cache.GetEnumerator()
While enumerator.MoveNext()
	Dim key As String = CType(CType(enumerator.Current, DictionaryEntry).Key, String)
	If key.StartsWith('cachedata_') Then
	                ’ Print it:
                	Response.Write(('Deleting key ' + key + '
'))
	                ’ Remove it:
                	Cache.Remove(key)
	End If
End While

C#

IDictionaryEnumerator enumerator = Cache.GetEnumerator();
while(enumerator.MoveNext()) 
{
	String key = (String) ((DictionaryEntry) enumerator.Current).Key;
	if(key.StartsWith('cachedata_')) 
	{
		// Print it:
		Response.Write('Deleting key ' + key + '
');
		// Remove it:
		Cache.Remove(key);
	}
}
Permalink
Is there a Cache.RemoveAll()? How can I clear / remove the total cache

VB.NET

Dim objItem As DictionaryEntry
For Each objItem In  Cache
   ’Response.Write (objItem.Key.ToString ());
   Cache.Remove(objItem.Key.ToString())
Next

C#

foreach(DictionaryEntry objItem in Cache) 
{ 
	//Response.Write (objItem.Key.ToString ());
	Cache.Remove(objItem.Key.ToString () ) ;
}
Permalink
How to display items stored in a local application Cache

VB.NET

Dim objItem As DictionaryEntry
For Each objItem In  Cache
   	Response.Write(('Key :' + objItem.Key.ToString() + '
'))
   	Response.Write((' Value :' + objItem.Value.ToString() + '
'))
Next

C#

foreach(DictionaryEntry objItem in Cache) 
{ 
	Response.Write ('Key :' + objItem.Key.ToString () + '
');
	Response.Write(' Value :' + objItem.Value.ToString ()+ '
' ) ;
}
Permalink
How to access the Cache from a compiled class

VB.NET

somevar=System.Web.HttpContext.Current.Cache('<cachename>')
</cachename>

C#

somevar=System.Web.HttpContext.Current.Cache('<cachename>');
</cachename>
Permalink
Why do I get the error message ‘The type or namespace name ‘CacheDependency’ could not be found (are you missing a using directive or an assembly reference?) ‘

Use namespace System.Web.Caching or
refer to it as System.Web.Caching.CacheDependency

Permalink
How do I access the cache in the Global.asax

Use HttpRuntime.Cache

Permalink
How can I programatically invalidate the outputcache from a usercontrol

You could add a dependency to the output cached control, and change the dependency to evict the control. Here’s code to do that:

VB.NET

If TypeOf Parent Is System.Web.UI.BasePartialCachingControl Then
            	Cache('dependent') = 'dependent'
            	Dim dep As New CacheDependency(Nothing, New String() {'dependent'}) ’
            	CType(Parent, System.Web.UI.BasePartialCachingControl).Dependency = dep
End If

C#

if (Parent is System.Web.UI.BasePartialCachingControl) 
{ 
	Cache['dependent'] = 'dependent'; 
	CacheDependency dep = new CacheDependency(null, new string[] 'dependent'); 
	((System.Web.UI.BasePartialCachingControl)Parent).Dependency = dep; 
}
Permalink
Is caching PDF Files a good or bad idea

If the PDF files are on the disk, you should just let the IIS handle them. The IIS static file handler performs caching and is much faster than the ASP.NET cache.

Permalink