Saturday, 7 September 2013

Caching ( MVC )

Caching in MVC applications provides facility to cache the output of controllers and improve your application performance to many times.The output cache enables you to cache the content returned by a controller action.
There are you ways to use output cache in your mvc applications :
  1. Declare on the top of the action ( or controller which will be applied on all actions inside it )
  2. Create Cache Profile ( define caching section inside web.config of your application)

Declare on top of controller or action:
 You can specify cache for an action or controller by writing this line on the top of it , like this ,

OutputCache(Duration=30, varyByParam="none" , Locaiton=OutputCacheLocationClient, NoStore=true)]

You can set the Location property to any one of the following values:
· Any
· Client
· Downstream
· Server
· None
· ServerAndClient

Creating Cache Profile:

Define profile inside of system.web section of your web.config like this :

        <add name="myCache" duration="3600" varyByParam="none"/>
And you can then use this profile like that :
        public string Index()
            return DateTime.Now.ToString("T");
In both of above cases "varyByParam" is a very important parameter , this actually enables us to create different cache versions of the same view ( request ) , for example on the basis of user id we are differentiating out views , so in that case we can set varyByParam to id so that different versions of cache are available for different users accordingly , very dynamic and easy solution.
For further reading you can go to : "".