Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Caching in Web API

4.08/5 (9 votes)
25 Mar 2016CPOL6 min read 43.9K   1  
How to use caching in Web API

In this article, we will are going to learn how we can use caching in Web API. Normally, caching is the process of storing data somewhere for future requests, in our case we can avoid the unwanted hit to database to get the data if we cache the data somewhere, this way we can make sure that the data is served in a faster manner. Here we are going to see the caching in our Web API controller. If you are new to caching, I have written an article about caching in MVC, please read it here: Caching In MVC. We will explain caching with the help of System.Runtime.Caching which is given by Microsoft. This DLL is not available in the default references, you may need to add that separately. I will show you how. I am creating this application in Visual Studio 2015. You can always get the tips/tricks/blogs about these mentioned technologies from the links given below:

Now, we will go and create our application. I hope you will like this.

Background

For the past few days, I have been working with Web API. Here, we are going to see a demo of how to use Caching in Web API in our MVC application. We are going to use the DLL System.Runtime.Caching.dll, which you need to add as reference.

Create an MVC Application

Click File-> New-> Project, then select MVC application. From the following pop up, we will select the template as empty and select the core references and folders for MVC.

Empty Template With MVC And Web API Folders

Empty Template With MVC And Web API Folders

Once you click OK, a project with MVC like folder structure with core references will be created for you.

Folder Structure And References For Empty MVC Project

Folder Structure And References For Empty MVC Project

Once your application is ready, we can add the reference for System.Runtime.Caching.

Add Reference for System.Runtime.Caching

To add the reference, right click on References and click Add reference.

Add_References

Add_References

Now click on the browse button, and search for System.Runtime.Caching.

References_Found_

References_Found_

And then click OK, the DLL will be added to your references now.

Using the Code

We will set up our database first so that we can create Entity Model for our application later.

Create a Database

The following query can be used to create a database in your SQL Server.

SQL
USE [master]
GO

/****** Object:  Database [TrialsDB]    
CREATE DATABASE [TrialsDB]
 CONTAINMENT = NONE
 ON  PRIMARY 
( NAME = N'TrialsDB', _
FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf' , _
SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'TrialsDB_log', _
FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf' , _
SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO

ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110
GO

IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO

ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF 
GO

ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF 
GO

ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF 
GO

ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF 
GO

ALTER DATABASE [TrialsDB] SET ARITHABORT OFF 
GO

ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF 
GO

ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON 
GO

ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF 
GO

ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON 
GO

ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF 
GO

ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT  GLOBAL 
GO

ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF 
GO

ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF 
GO

ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF 
GO

ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF 
GO

ALTER DATABASE [TrialsDB] SET  DISABLE_BROKER 
GO

ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF 
GO

ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF 
GO

ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF 
GO

ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF 
GO

ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE 
GO

ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF 
GO

ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF 
GO

ALTER DATABASE [TrialsDB] SET RECOVERY FULL 
GO

ALTER DATABASE [TrialsDB] SET  MULTI_USER 
GO

ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM  
GO

ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF 
GO

ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF ) 
GO

ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS 
GO

ALTER DATABASE [TrialsDB] SET  READ_WRITE 
GO

Now, we will create the table we needed. As of now, I am going to create the table tblTags.

Create Tables in Database

Below is the query to create the table tblTags.

SQL
USE [TrialsDB]
GO

/****** Object:  Table [dbo].[tblTags]    Script Date: 23-Mar-16 5:01:22 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[tblTags](
	[tagId] [int] IDENTITY(1,1) NOT NULL,
	[tagName] [nvarchar](50) NOT NULL,
	[tagDescription] [nvarchar](max) NULL,
 CONSTRAINT [PK_tblTags] PRIMARY KEY CLUSTERED 
(
	[tagId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, _
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

Can we insert some data to the tables now?

Insert Data to Table

You can use the below query to insert the data to the table tblTags.

SQL
USE [TrialsDB]
GO

INSERT INTO [dbo].[tblTags]
           ([tagName]
           ,[tagDescription])
     VALUES
           (<tagName, nvarchar(50),>
           ,<tagDescription, nvarchar(max),>)
GO

Next thing we are going to do is creating a ADO.NET Entity Data Model.

Create Entity Data Model

Right click on your model folder and click new, select ADO.NET Entity Data Model. Follow the steps given. Once you have done the processes, you can see the edmx file and other files in your model folder. Here I gave Dashboard for our Entity data model name. Now, you can see a file with edmx extension has been created.
Now, we will create our Web API controller.

Create Web API Controller

To create a Web API controller, just right click on your controller folder and click Add -> Controller -> Select Web API 2 controller with actions, using Entity Framework.

Web API 2 Controller With Actions Using Entity Framework

Web API 2 Controller With Actions Using Entity Framework

Now select tblTag (CachingInWebAPI.Models) as our Model class and TrialsDBEntities (CachingInWebAPI.Models) as data context class.

As you can see, it has been given the name of our controller as tblTags. Here, I am not going to change that, if you wish to change, you can do that.

Now, you will be given the following codes in our new Web API controller.

C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using CachingInWebAPI.Models;

namespace CachingInWebAPI.Controllers
{
    public class tblTagsController : ApiController
    {
        private TrialsDBEntities db = new TrialsDBEntities();

        // GET: api/tblTags
        public IQueryable<tblTag> GettblTags()
        {
            return db.tblTags;
        }

        // GET: api/tblTags/5
        [ResponseType(typeof(tblTag))]
        public IHttpActionResult GettblTag(int id)
        {
            tblTag tblTag = db.tblTags.Find(id);
            if (tblTag == null)
            {
                return NotFound();
            }

            return Ok(tblTag);
        }

        // PUT: api/tblTags/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PuttblTag(int id, tblTag tblTag)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != tblTag.tagId)
            {
                return BadRequest();
            }

            db.Entry(tblTag).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!tblTagExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/tblTags
        [ResponseType(typeof(tblTag))]
        public IHttpActionResult PosttblTag(tblTag tblTag)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.tblTags.Add(tblTag);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = tblTag.tagId }, tblTag);
        }

        // DELETE: api/tblTags/5
        [ResponseType(typeof(tblTag))]
        public IHttpActionResult DeletetblTag(int id)
        {
            tblTag tblTag = db.tblTags.Find(id);
            if (tblTag == null)
            {
                return NotFound();
            }

            db.tblTags.Remove(tblTag);
            db.SaveChanges();

            return Ok(tblTag);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool tblTagExists(int id)
        {
            return db.tblTags.Count(e => e.tagId == id) > 0;
        }
    }
}

As we are not going to use only read operation, you can remove other functionalities and keep only Get methods for now.

C#
// GET: api/tblTags
       public IQueryable<tblTag> GettblTags()
       {
           return db.tblTags;
       }

So the coding part to fetch the data from database is ready, now we need to check whether our Web API is ready for action!. To check that, you just need to run the URL http://localhost:4832/api/tblTags. Here tblTags is our Web API controller name. I hope you get the data as a result.

Web_API_Result

Web_API_Result

Now, we will start testing our caching. For that, please import the namespace System.Runtime.Caching;

C#
using System.Runtime.Caching;

Next, we will create an instance of MemoryCache class.

MemoryCache_Tooltip_

MemoryCache_Tooltip_

As you can see, there are four possible settings we can set in MemoryCache class.

MemoryCache_Settings

MemoryCache_Settings

 

Now, we can add MemoryCache as follows:

C#
public IQueryable<tblTag> GettblTags()
        {
            var ca = db.tblTags;
            memCache.Add("tag", ca, DateTimeOffset.UtcNow.AddMinutes(5));
            return db.tblTags;
        }

MemoryCache_Add

MemoryCache_Add

Here “tag” is my key and “ca” is my value and DateTimeOffset.UtcNow.AddMinutes(5) is for setting the cache for five minutes from now.

Shall we check how it works now? To check whether the content has been added to the cache, we need to use the Get method, please see the code block below.

C#
var res = memCache.Get("tag");
            if (res != null)
            {
                return res;
            }
            else {
                var ca = db.tblTags;
                memCache.Add("tag", ca, DateTimeOffset.UtcNow.AddMinutes(5));
                return db.tblTags;
            }

We will get the cache values in the variable res, remember these values will be there only for five minutes. You can always change that as per your requirement. If the value is not null, we will just return it and do the manipulation and if it is null, we will go ahead and fetch the data from database and add the value to cache. Now, please run your API by running the URL http://localhost:4832/api/tblTags.

Cache_Value_Null

Cache_Value_Null

You can see that we are setting the value to memCache as the memCache.Get(“tag”) is null.

Cache_Value_Not_Null

Cache_Value_Not_Null

So we just tried to load the same Web API URL within five minutes, so we get values from memCache.Get(“tag”). Sounds good?

There is an option to remove our cache too, we will see that now. We will use the Remove function for the same. First, we will check whether the key is available in the MemoryCache, if it is available we will remove that.

C#
//This is to remove the MemoryCache - start
                if (memCache.Contains("tag"))
                {
                    memCache.Remove("tag");
                }
                //This is to remove the MemoryCache - end

MemoryCache_Remove

MemoryCache_Remove

We have done everything!. That’s fantastic, right? Happy coding.

Conclusion

Did I miss anything that you may think is needed? Did you try Web API yet? Have you ever wanted to do caching in Web API? Could you find this post useful? I hope you liked this article. Please share your valuable suggestions and feedback.

Your Turn. What Do You Think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, ASP.NET Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)