Open In App

ASP.NET MVC Caching

Last Updated : 22 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Caching is the data store just like a database but slightly it is different cache stores, its data in memory so it does not interact with the file system. It also stores data in very simple structures like key-value pairs. So they don’t have to execute complex queries to gather data and maintain indexes when they write. Because of this reason cache is more performant than a database

Reason to use the cache,

  • To increase the performance of your application because data in cache lives in memory.
  • The cache can increase the uptime of the application because it is still there if your database is unreachable.

But before applying the caching attribute you should think about it.

The first thing is that you should carefully pick the data that you are going to add to the cache like suppose you are caching the data which is updated every millisecond then there is no meaning to cache that type of data, so typically you should cache data that is accessed often and doesn’t change often.

And this feature we can implement in asp.net MVC using Output cache attributes for it.

In this, you learn how to cache the output returned from a controller action so that a new user doesn’t need to create the same content every time the action is called.

Using the OutputCache attribute, you can enable output caching functionality by applying an individual controller action or an entire controller class.

So let’s see the properties of OutputCache one by one:

Duration: It represents the time in seconds that user output cached. Property Value: Int32

Syntax: 

[OutputCache(Duration=Specify_time)]

Example: Let’s see with an example:

C#




using System.Web.Mvc;
  
namespace Caching_DataDemo.Controllers {
    public class CacheController : Controller {
        // GET: Cache
        [OutputCache(Duration = 20)]
            public ActionResult GetDate() {
            return View();
        }
    }
}


As you see in the above snippet we have enabled output cache on the controller action level.it cached the output for 20 seconds.

If you call the GetDate() action several times by entering the URL /Cache/GetDate in your browser and clicking the Refresh button in your browser repeatedly, then the time displayed by the GetDate view won’t change for 20 seconds. At the same time output is displayed because the view is cached.

You can cache the output for 1 day by specifying the time but when memory resources go low or down, the cache starts eliminating the content automatically so there is no guarantee that content will be cached for the time which you specify.

HTML




@{
    Layout = null;
}
  
<h2>GetDate</h2>
<div>
    <h3>The Current time : 
      @DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss")</h3>
</div>


The GetDate view just displays the current time.

Now the question is Where actually those cache content stored. When we use the [OutputCache] attribute, the content is cached in locations that are defined in the OutputCacheLocation enum.

You can cache data in any location by modifying the location property of [OutputCache]. 

Location: Property value: String. Location property values you can set:

  1. Any: by default consider this value. and in this case, content is cached in any one of three locations: the webserver(where the request is processing.), any proxy servers (other server involved in the request), and the web browser(from where the request is generated).
  2. Client: In this case, the output cache will be stored on the browser client from where the request is originated.
  3. Server: In this case, the output cache will be stored server where the request is processing.
  4. None: In this case, output cache will be disabled for the requested web page
  5. Server and Client: In this case. output cache will be stored either at the origin server or at the requesting client

By default value of location, the property is Any. Might be there is some situation in that you want to cached data on a particular location in that scenario you can use this property.

Lets consider the one scenario, 

C#




using System.Web.Mvc;
  
namespace Caching_DataDemo.Controllers {
    public class CacheController : Controller
    {
        // GET: Cache
        [OutputCache(Duration = 20, 
            Location = OutputCacheLocation.Server)]
        public String GetIdentityofUser()
        {
            return "Good Morning !" + User.Identity.Name;
        }
    }
}


Well, As you can see, In the above code we are caching the user identity data for 20 seconds on the Server level. In the code snippet, there is one controller i.e CacheController which action method name GetIdentityofUser() that returns Greeting message with the current login user Identity.

Now If one of a person like consider name Lucifer login into the website and called the GetIdentityofUser() then the action return “Good Morning ! Lucifer ”.and in between specified cache duration other subsequently login into the website then that person will get the same string output because the string is cached on the server level.

[OutputCache(Duration =20,Location=OutputCacheLocation.Server)]

Note: Never cache personalized content in server cache.

you might want to cache personalized content in the browser cache to improve performance. and If you cache the content in the browser, and a user called the same controller action several times, then the content may be retrieved from the browser cache instead of the server.

Let’s modify that way, Just simply replace the Output cache location Server to Client so it will cache the output only on browser.

[OutputCache(Duration =20,Location=OutputCacheLocation.Client)]

Now, every user will get their own identity.

NoStore: Indicating whether secondary storage is enabled or not. its default value is set to False. Property value: Boolean Type.

We can also add NoStore property. The NoStore property is used to inform proxy servers and browsers that they should not store a permanent copy of the cached content.

[OutputCache(Duration =20, Location=OutputCacheLocation.Client, NoStore=true)]

VarByParam: Varying the Output Cache: it is used to implement different cache versions of the output based on input parameters by using.

Consider a scenario, Suppose, we have a controller called ProductRecordController and it has one action method DetailsOfProduct which displays details of the product based on id. which means this method takes id as the input parameter and based on that id parameter it displays information of the product. Now we want to create a different cache version of the details view of the product based on the input parameters.

Let’s implement it,

C#




[OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
public ActionResult DetailsOfProduct(int? id)
{
    Product item = db.Products.Find(id);
    return View(item);
}


As you can see in the code, the id parameter is set to VaryByparam property so now every different value of the Id parameter is passed to the controller action, different cached versions of the DetailsOfProduct view are generated.

Cacheprofile: This is actually another approach to define output cache attribute, you can create a cache profile in the web.config file.

OutputCacheProfile: It is an object centralizes in which we configure frequently access settings such as cache location and expiration time so on.

This approach offers some advantages.

First, Central cache control. Simply by just creating a cache profile in the web config file. You can apply the profile to several controllers or controller actions. Instead of defining the same code at multiple places, the resulting code is duplicated.

Second, you can easily modify your profile without recompiling. If you need to disable it for an application that has already been deployed to production, then also you can simply modify the cache profiles defined in the web configuration file. Any changes which we make to the web configuration file will be detected automatically and applied.

Example: Let’s see the example:

XML




<caching>
    <outputCacheSettings>
        <outputCacheProfiles>
            <add name="TimeCacheProfile" duration="30" 
                 enabled="true" varyByParam="none" />
        </outputCacheProfiles>
    </outputCacheSettings>
</caching>


Here, you can see we have added configuration in add element of the OutputCacheProfiles section in the caching section of the configuration file.

C#




using System;
using System.Web.Mvc;
  
namespace MvcApplication.Controllers
{
    public class ProfileController : Controller
    {
        [OutputCache(CacheProfile="TimeCacheProfile")]
        public string Index()
        {
            return DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss");
        }
    }
}


and I have applied that profile to a controller action using the CacheProfile attribute of OutputCache

OutputCache(CacheProfile="TimeCacheProfile")]

If you run the code, then the current time date will remain the same for 30 seconds as we have set the duration property to 30 seconds in cache profile. So it will cache the content for 30 sec.

Finally, you learned how and when to use the OutputCache attribute in ASP.NET MVC



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads