Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Saturday, 21 January 2017

OutputCache Action Filter in ASP.Net MVC

In this article, we will learn, how to use OutputCache Action filter in ASP.NET MVC Applications. In previous ASP.NET MVC tutorials of this series, we saw,



One of the best way to improve the performance of an ASP.NET MVC application is by caching. With the help of Caching, we can reduce hosting and database server round trips. We can apply Outputcache action filter either on Action Method or on the controller. OutputCache attribute has several properties like CacheProfile, Duration, Location, VaryByParam, VaryByHeader, NoStore etc.
Let’s create a simple example so that we can understand Outputcache attribute better.

Let’s Begin:
Create a new ASP.NET MVC application.
Select Empty MVC application and Click on OK.
For this example, I have created a database (named as DemoDB) with a table (Employee) having schema as below: (I will use Entity framework with Database first approach in this example, you can use any with which you feel comfortable)
CREATE TABLE dbo.Employee
       (
       ID   INT IDENTITY NOT NULL,
       Name NVARCHAR (100) NULL,
       City NVARCHAR (100) NULL,
       CONSTRAINT PK_Employee PRIMARY KEY (ID)
       )
GO
Right click on Models and then Click on Add new item. Select ADO.NET Entity Data Model. Give it a meaningful name and click on Add.
Select EF Designer from database and Click on next.
Create New Connection and select version of Entity framework you want to use.

Select database objects you want to add in your model and click on finish.
After that, you will see Employee Entity in Designer.
Now Right click on the controller and add an Empty controller.
Bind Employee data to the view
public ActionResult Index()
{
    DemoDBEntities db = new DemoDBEntities();
    var Employees = db.Employees.ToList();
    return View(Employees);
}
Index.cshtml Code:
@model IEnumerable<OutputCacheApplication.Models.Employee>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <div class="container">
        <div class="row">
            <div>
                <div class="alert alert-info"><b>Data Collected @@ @DateTime.Now.ToString()</b></div>
            </div>
        </div>
        <div class="row">
            <div>
                <table class="table table-striped">
                    @foreach (var item in Model)
                    {
                        <tr><td>@item.ID</td><td>@item.Name</td><td>@item.City</td></tr>
                    }
                </table>
            </div>
        </div>
    </div>
</body>
</html>
Build and Run the application. Whenever we refresh the page, get request is sent to the Index Action of Home Controller.
Preview:

Let’s add Output cache action filter on Index action method.
[OutputCache(Duration = 10, VaryByParam = "none")]
public ActionResult Index()
{
        DemoDBEntities db = new DemoDBEntities();
        var Employees = db.Employees.ToList();
        return View(Employees);
}
Here we set Duration to 10 sec which means cached ActionResult/output will be expired after 10 sec. Now Build and Run the application.
Preview:
If memory resources are lower than ASP.NET clears the items from the cache before completing its duration/Expiry time.

Example of OutputCache with Location Property:
By using the Location property of output cache, we can control where output is cached. For example, if we want to cache some personal information then it is recommended to catch it on the client. If output data is private/confidential then it is recommended not to store it in the cache.
[OutputCache(Duration = 10, VaryByParam = "none", Location = System.Web.UI.OutputCacheLocation.Client)]
public ActionResult Index()
{
      DemoDBEntities db = new DemoDBEntities();
      var Employees = db.Employees.ToList();
      return View(Employees);
}
OutputCache filter adds appropriate cache control header in response based upon Location property.

Example of OutputCache with VaryByParam attribute:
VaryByParam property creates a different cache based upon the parameter value passed through Query String or Request.Form.
[OutputCache(Duration =20,VaryByParam ="ID")]
public ActionResult SearchRecord(int ID)
{
      DemoDBEntities db = new DemoDBEntities();
      var Employees = db.Employees.Where(x=>x.ID==ID).ToList();
      return View("Index", Employees);
}
Preview:
Example of OutputCache with CacheProfile:
If we want to same type of OutputCache properties on multiple Action method or multiple controller then we can use CacheProfile property. CacheProfile have several advantages for example, we can change OutputCache property at multiple places from one central location and will apply without recompiling our application. Add Caching section in system.web section which will containg OutputCacheSettngs. In OutputCacheSettngs, we have added outputCacheProfiles with name and other properties.
<caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="CacheFor20Seconds" duration="20" varyByParam="none" location="Server"/>
        </outputCacheProfiles>
      </outputCacheSettings>
</caching>
Now go to your Action method or controller, and add CacheProfile property in OutputCache action filter.
[OutputCache(CacheProfile = "CacheFor20Seconds")]
public ActionResult WorkingWithCacheProfile()
{
    DemoDBEntities db = new DemoDBEntities();
    var Employees = db.Employees.ToList();
    return View("Index",Employees);
}

0 comments:

Post a Comment

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook