Saturday, 24 December 2016

What is Caching? Explain Output Cache.

Caching is a most important aspect of high-performance web application. Caching provides a way of storing frequently accessed data and reusing that data. Practically, this is an effective way for improving web application’s performance.
Output Cache can dramatically improve the performance of an ASP.NET MVC application. The output cache enables you to cache the content returned by a controller action. That way, the same content does not need to be generated each and every time the same controller action is invoked.
The OutputCache filter allow you to cache the data that is output of an action method. By default, this attribute filter cache the data till 60 seconds. After 60 sec, if a call was made to this action then ASP.NET MVC will cache the output again.
Enabling Output Caching
You enable output caching by adding an [OutputCache] attribute to either an individual controller action or an entire controller class as below.
[OutputCache(Duration=10, VaryByParam="none")]
        public ActionResult Index()
        {
            return View();
        }
Output Caching Location
By default, content is cached in three locations: the web server, any proxy servers, and the user's browser. You can control the content's cached location by changing the location parameter of the OutputCache attribute to any of the following values: 
  • Any (Default): Content is cached in three locations: the web server, any proxy servers, and the web browser.
  • Client: Content is cached on the web browser.
  • Server: Content is cached on the web server.
  • ServerAndClient: Content is cached on the web server and and the web browser.
  • None: Content is not cached anywhere.
[OutputCache(Duration=3600, VaryByParam="none", Location=OutputCacheLocation.Client, NoStore=true)]
        public string GetName()
        {
            return "Hi " + User.Identity.Name;
        }
Varying the Output Cache
In some situations, you might want different cached versions of the very same content, So for that we use "VaryByParam" as in above code.
In case we have multiple action methods across controllers needing the same caching behavior, we can put this caching values in the web.config and create a cacheprofile for it.
<caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="MyCacheProfile"
               duration="30"
               varyByParam="id"
               location="Any" />
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
And to use these values in the action methods we just need to specify the CacheProfile name in the action method.
[OutputCache(CacheProfile = "MyCacheProfile")]
public ActionResult Dummy()
{  
    return View();
}
For more Cache MSDN Cache

No comments:

Post a Comment