Caching pages with cusom conditions – ASP.Net MVC

Hi Folks,

If you are a .Net web developer, then you may heart about the caching mechanism that available in the ASP.Net. The caching allows to load the pages very fast by storing the page date in the server. So when you make a request for the first time the page, the APS.Net engine will go through the regular page rendering process and store the rendered page data in the server. When a request comes to show that page again, the sever simply return the cached date instead of go through all the process again and that gives a big performance improvement in your site.

For example, you have a site that has around 100 menus and those menus are displayed on each page. Lets’ consider there are around 100 request per minute to server to generate those menus. Then generating the menus will take significant of server process to generate the menus 100 time. By caching the menu data, the server will process the menu creation for the first time and the reaming 99 times the server simply return the cached data.

Here we’ll see how we can implement the caching and how to add custom caching according to the request pattern.


Adding caching

It’s very simple process, just add the annotation attributes according your caching requirement.

the below code, cache the acction for 1000 seconds.

If you want to cache the action using the action paraments then simply add those parameters to OutputCache.

Refer here more info


The most important one, having our dynamically ching custom condition.

let’s say your page behave differently according to the logged-in users, then we need cache the data according to the logged-in user. This can be achieved by using “VaryByCustom” and need to override the default behavior of the cache key creation.

The action will be like;

The method that need to be override is “GetVaryByCustomString” and it goes to “Global.asax.cs” class.


The caching works by storing the data in the serving. So each data is identified using a cache key. So the main role of the GetVaryByCustomString function is to create a unique key for different request.


Do more caching and increase the site performance. But note that, if you are caching all request then the server may be slow due to out of memory 🙂

You may also like...

Leave a Reply

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

%d bloggers like this: