Cache In Asp.Net MVC

18:08

Introduction

The purpose of this article is what is caching and its type and how to use caching in MVC application.

What Is Caching

Caching is a technique of storing frequently used data in memory, so that, when the same data or information is needed next time, it could be directly retrieved from the memory instead of being generated by the application.

Why We Use Caching

We are mostly involved in developing web pages that are dynamic, i.e. data coming from databases, Server directories, XML files or some other websites. Caching helps to store this data which is being used frequently. So that our application provide better performance.

Cache Location

This property using in PageOutputCache attribute class. It will determine where will the cached data be stored on the server. Possible values for this property can be:
i) Any (Default): Content is cached in three locations: the web server, any proxy servers, and the web browser.
ii) Client: Content is cached on the web browser.
iii) Server: Content is cached on the web server.
iv) ServerAndClient: Content is cached on the web server and and the web browser.
v) None: Content is not cached anywhere.

Cache Parameter

Mainly cache have two parameter:
i) Duration: Duration time that data will store in cache
ii) VaryByParam: List of strings that are sent to server via HTTP POST/GET that are checked to validate cache
Other Type:

iii) VaryByCustom: Used for custom output cache requirements
iv) VaryByHeader: HTTPS header that determines the cache validity
v) SqlDependency: Defines the Database-tablename pair on which the validity of cache depends

Types Of Caching

There are two types of caching available in ASP.NET:
I) Page output Caching
II) Application Caching

I. Page Output Caching

Page output cache stores a copy of the finally rendered HTML pages or part of pages sent to the client. When the next client requests for this page, instead of regenerating the page, a cached copy of the page is sent, thus saving time.

Example 1: Without caching

Controller:
    public class TestController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }      
    }
View:
@{
    Layout = null;
}

<h2>Simple page without caching</h2>


Date Time is: @DateTime.Now.ToString()
Output:
If we run this application it show the current datetime. And if we refresh the page it will show the updated time.

Example 2: Using caching with Duration and VaryByParam "none"

Controller:
    public class TestController : Controller
    {
        [OutputCache(Duration = 10, VaryByParam = "none")]
        public ActionResult Test()
        {
            return View();
        }
    }
View:
@{
    Layout = null;
}

<h2>Using caching with duration "10", and VaryByParam "none"</h2>


Date Time is: @DateTime.Now.ToString()
Output:
If we run this application it show the current datetime. And if we refresh the page it will not show the updated time. The time will be update after 10 seconds because caching duration time is 10 second.

Example 3: Using caching with Duration and VaryByParam "id"

Controller:
    public class TestController : Controller
    {
        [OutputCache(Duration = 10, VaryByParam = "id")]
        public ActionResult Test()
        {
            return View();
        }
    }
View:
@{
    Layout = null;
}

<h2>Using caching with duration "10", and VaryByParam "id"</h2>


Time is @DateTime.Now.ToString()
Output:
If we run this application it show the current datetime. And if we refresh the page it will not show the updated time. The time will be update after 10 seconds id we send with parameter "id" because caching duration time is 10 second and using parameter.

Smarter Ways To Use Cache

If we need to use same cache in all the action result. We use like this:
    public class TestController : Controller
    {
        [OutputCache(Duration = 10, VaryByParam = "none")]
        public class TestController : Controller
        {   
            public ActionResult Index1()
            {
                return View();
            }

            public ActionResult Index2()
            {
                return View();
            }
        }
    }

More Easyest Process To Use Cache

In case we need to use cache in multiple action methods across controllers, we can put this caching values in the web.config and create a cacheprofile for it.
Web.config:
  <system.web>
    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="CacheProfile" 
               duration="10" 
               varyByParam="id" 
               location="Any" />
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
Controller:
    public class TestController : Controller
    {
        [OutputCache(CacheProfile = "MyCacheProfile")]
        public class TestController : Controller
        {   
            public ActionResult Index1()
            {
                return View();
            }

            public ActionResult Index2()
            {
                return View();
            }
        }
    }

Use Cache In Partial Page

Controller:
    public class TestController : Controller
    {
        public ActionResult MainPage()
        {
            return View();
        }

        [OutputCache(Duration = 10, VaryByParam = "none")]
        public PartialViewResult PartialPage()
        {
            return PartialView("SamplePartial");
        }
    }
Main Page View:
@{
    Layout = null;
}

<h2>Cache Using In Partial Page</h2>


Time is @DateTime.Now.ToString()

<br /><br />
Partial page here: @Html.Action("PartialPage")
Partial Page View:
@{
    Layout = null;
}

<h2>Partial Page</h2>

Date Time is @DateTime.Now.ToString()
Output:
Partial page is refresh after 10 seconds.

No Cache

If we don't want any cache in our action result. Then follow the code below:
Controller:
    public class TestController : Controller
    {
        [NoCache]
        public ActionResult NoCaching()
        {
            return View();
        }
    }
Class Code:
    public class NoCache : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
            filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
            filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            filterContext.HttpContext.Response.Cache.SetNoStore();
            base.OnResultExecuting(filterContext);
        }
    }

II. Application Caching

Application data caching is a mechanism for storing the Data objects on cache. It has nothing to do with the page caching. ASP.NET allows us to store the object in a Key-Value based cache. We can use this to store the data that need to cached.
We try to store the DateTime string in the Application Cache
Controller:
    public ActionResult Test3()
    {
        if (System.Web.HttpContext.Current.Cache["time"] == null)
        {
            System.Web.HttpContext.Current.Cache["time"] = DateTime.Now;
        }

        ViewBag.Time = ((DateTime)System.Web.HttpContext.Current.Cache["time"]).ToString();
        return View();
    }
View:
@{
    Layout = null;
}

<h2>Application Cache</h2>


Time is @ViewBag.Time
Output:
Now if we run the application we will see the time. But no matter how many times, we refresh this page, the time value will not change. Because the value is coming from the Application cache. Also, we are not invalidating the cache at all.

Conclusion

I explain cache and its all properties. If I missed something to explain then please leave a comment.

You Might Also Like

0 comments