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 {
[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:
- 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).
- Client: In this case, the output cache will be stored on the browser client from where the request is originated.
- Server: In this case, the output cache will be stored server where the request is processing.
- None: In this case, output cache will be disabled for the requested web page
- 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
{
[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
Similar Reads
ASP.NET MVC Life Cycle
The goal of this article is to provide a good understanding of the MVC pipeline. The life cycle is basically is set of certain stages which occur at a certain time. MVC actually defined in two life cycles, the application life cycle, and the request life cycle. The application life cycle, in which t
8 min read
Caching in Next.js
Caching is all about storing copies of the data in temporary storage, and that stored data is called cache. The main reason to do caching is that, in the future, when that data is needed, it can be served faster, and we don't have to fetch the data from the original source, because that can take som
5 min read
ASP Contents Collection
The ASP Contents Collection is used for collecting the items which are appended to the Application object by using script command. This Collection can also be used to provide a list of items that have been given application scope, The Contents.Remove and Contents.RemoveAll methods can be used to rem
1 min read
Caching Strategies for API
The article explains how to improve the performance and efficiency of APIs using caching. Caching is a technique where frequently accessed data is stored temporarily to reduce the time and resources needed for future requests. The article discusses different methods and strategies for implementing c
10 min read
What is Pre-Caching?
Pre-caching is like getting ready for something before it happens. Imagine you're going on a trip and you pack your bag the night before so you're all set to go in the morning. That's pre-caching! In the digital world, it's when your device stores information ahead of time, like loading a webpage be
13 min read
Middleware in ASP.NET Core
In this article, we will understand what middleware is in asp.net core. A Middleware is a very broad term in asp.net core middleware is a piece of software that can handle an HTTP request or response. For example, we may have a middleware of a component that authenticates a user, another piece of mi
4 min read
ASP Clear Method
The ASP Clear Method is used to clear or erase an Buffered HTML Output. This method only erases the response Body, It does not affect the response Headers. When the Response.buffer is set to false, It will show an error message after calling. Syntax: response.Clear Parameter Values: It does not cont
1 min read
ASP Request.Form Collection
The Request.Form Collection in ASP is used for returning the collection of form elements that posted to the HTTP request body, with a form using the POST method. Syntax Request.Form( element )[(index)|.Count] Parameter: Element: It specifies the name of the form elements. It is a required attribute.
1 min read
ASP CacheControl Property
The ASP CacheControl Property is used to set whether a proxy server can cache the HTML Output or not which have been generated by the ASP The proxy servers configured to cache Web pages for faster response times. Basically, ASP pages are developed to be unique for each user or may contain secure inf
1 min read
What are In-Memory Caches?
In-memory caches are essential tools in modern computing, providing fast access to frequently used data by storing it in memory. This article explores the concept of in-memory caches, their benefits, and their role in enhancing system performance and scalability. Important Topics for In-Memory Cache
12 min read