ASP.NET MVC > Web API

Caching in Web API in ASP.NET MVC

How to cache data being returned from ASP.NET Web API?


To cache the data being returned from ASP.NET Web API, we can use MemoryCache object that is the part of System.Runtime.Cache namespace. Please note that OutputCache attributes to the controller action method of ASP.NET MVC is not supported in ASP.NET Web API.

Right click the project and select Add > Reference…, the below dialog appears.

Select System.Runtime.Caching checkbox and click OK button. This adds System.Runtime.Caching.dll in the bin folder of the application.

Now, create an action method in the API controller. To differentiate this GET method, we have passed a isCached parameter here.

CONTROLLER ACTION METHOD

// GET: api/PersonalDetailsAPI
        public IQueryable<PersonalDetail> GetPersonalDetailsCached(bool isCached)
        {
            var cache = MemoryCache.Default;

            if (cache.Get("dataCache") == null)
            {
                var cachePolicty = new CacheItemPolicy();
                cachePolicty.AbsoluteExpiration = DateTime.Now.AddSeconds(60);

                var data = db.PersonalDetails;
                cache.Add("dataCache", data.ToList(), cachePolicty);
                return data;
            }
            else
            {
                IEnumerable<PersonalDetail> data =
(IEnumerable<PersonalDetail>)cache.Get("dataCache");
               return data.AsQueryable();
            }
     }

First we are creating the object of the MemoryCache.Default object as cache. First we are checking for the key for which we are going to store data into Cache. If this is null (in the first request, of course it will be null). We are creating a CacheItemPolicy object and setting its AbsoluteExpiration to 60 seconds from current time.

Now we are getting the data from database into data variable and the same is being added with the help of Add method of the cache object with the key, the data from the database (after converting into List ie IEnumerable) and then cachePolicy just created. At last we are returning the data to the calling client.

In case, the data is already stored into the Cache, we are retrieving it from cache and converting this to IQueryable and returning to the calling client.

VIEW CODE

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <h2>Index Cached</h2>
    <table class="table">
        <tr>
            <th>Auto ID</th>
            <th>First Name
            </th>
            <th>Last Name
            </th>
            <th>Age
            </th>
            <th>Active
            </th>
        </tr>
        <tbody id="tableRows"></tbody>
    </table>
    <script type="text/javascript">
        $(function () {
            LoadAll();
        });

        function LoadAll() {
            $.ajax(
            {
                //url: '/api/PersonalDetails/GetPersonalDetails',
                url: 'http://localhost:58594/api/PersonalDetailsAPI/?isCached=true',
                type: 'GET',
                dataType: 'json',
                success: function (data, status, xhr) {
                    processDataMethod(data);
                },
                error: function (xhr, status, error) {
                    alert(error);
                }
            });
        }
function processDataMethod(data) { var output = $("#tableRows"); output.empty(); for (var i = 0; i < data.length ; i++) { var person = data[i]; output.append("<tr><td><a href='javascript:ShowDetails(" + person.AutoId + ")'>" + person.AutoId + "</a></td><td>" + person.FirstName + "</td><td>" + person.LastName + "</td><td>" + person.Age + "</td><td>" + person.Active + "</td></tr>"); } } </script>

In the above view, we are first referencing the jQuery file that we will be using to call the Ajax method. Next is the <table> element that is creating a tabular structure with the heading of the records to be listed. <tbody> element works as a placeholder where we will be populating the data retrieved from ASP.NET Web API.

In the script block, when the page loads, we are calling LoadAll() method that fires ajax method with the url of the Web API. After successful request and response, calls the processDataMethod function that intern loop through all records returned and append data into the <tbody> element by framing <tr><td> etc.

Running the page first gives the data from the database and saves that data into Cache and in the next request, the data comes from Cache till 60 seconds and after that cache data expires and again the fresh data is saved into cache for next 60 seconds and so on…

 Views: 5011 | Post Order: 128



Write for us