The main goal of this post is to explain how we can improve the performance of an ASP.NET MVC web application by using the advantage of the output cache. The output cache enables us to cache the information which is returned by an action. So it will not need to re-generated the action content every when the same action method is invoked. Caching play the main part of the web application, as it improves the performance and load on the server. ASP.NET MVC make is, very simply by adding the OutputCache attribute on the action method to our application.

Why Caching is needed ?

Lest we think of this, if we need to display a record from the database in a view. So if a user tries to view the same page repeatedly, then each and every time that a user invokes the controller action so it hit the database to fetch the record and returns to the user.

By using output cache, we canย avoid executing a database every time when user request the same controller action. At that time, it did retrieve the content from the cache instead of fetch them from the controller action. So the main advantage has enabledย us to avoid server overload that is performing redundant work on the server.

Required Namespace :

For configuring the cache location, we need to include the below namespace in our controller.
namespace : System.Web.UI

Set Cache Location

We can control the caching location by using the location parameter like following values Any, Client, Downstream, None, Server, or ServerAndClient. By default, the parameter will have the Any parameter for caching the content.

output Cache Attribute in MVC - dotnet-helpers

OutputCache parameters

output Cache Attribute in MVC parameters - dotnet-helpers

Enabling Output Caching

We can enable output caching by adding an OutputCache attribute to either an action or an entire controller class.

Controller Level Caching

Here in controller level caching, it’s cached all the action content under the control.

[OutputCache(Duration = 10, VaryByParam = “none” , Location = OutputCacheLocation.Client )] public class OutputCacheController : Controller { public ActionResult Index() { return View(); } }

ย Action Level Caching

In action level caching, the content has cached alone for that particular action method.

[OutputCache(Duration = 10, VaryByParam = “none” , Location = OutputCacheLocation.Client )] public ActionResult Index() { ViewBag.CurrentDataTimeMessage = DateTime.Now.ToString(); return View(); }

Here I had specified the cache duration as 10 seconds, so the cache content will be maintained up toย duration which we specified in the Duration parameter. When weย run the application, the Date Time will not change/update up to 10 seconds because it’s already cached from the action and maintain up to 10 seconds. So it won’t hit the action method.

 

Keep Cool Coding…