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 the 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.
Download the source code
You can always download the source code here.
Background
For the past few days I am 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 a 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.
Once you click OK, a project with MVC like folder structure with core references will be created for you.
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.
Now click on the browse button, and search for System.Runtime.Caching
And the 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
[/sql]
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
[/sql]
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
[/sql]
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 have been created.
Now 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.
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.
[csharp]
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;
}
}
}
[/csharp]
As we are not going to use only read operation, you can remove other functionalities and keep only Get methods for now.
[csharp]
// GET: api/tblTags
public IQueryable<tblTag> GettblTags()
{
return db.tblTags;
}
[/csharp]
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.
Now we will start testing our caching. For that please import the namespace System.Runtime.Caching;
[csharp]
using System.Runtime.Caching;
[/csharp]
Next we will create an instance of MemoryCache class.
As you can see there are four possible settings we can set in MemoryCache class.
Now we can add MemoryCache as follows.
[csharp]
public IQueryable<tblTag> GettblTags()
{
var ca = db.tblTags;
memCache.Add("tag", ca, DateTimeOffset.UtcNow.AddMinutes(5));
return db.tblTags;
}
[/csharp]
Here “tag” is my key and “ca” is my values 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.
[csharp]
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;
}
[/csharp]
We will get the cache values in the variable res, remember this values will be there only for five minutes. You can always change that as per need. 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.
You can see that we are setting the value to memCache as the memCache.Get(“tag”) is null.
So we just tried to load the same Web API URL within five minutes, so we gets 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.
[csharp]
//This is to remove the MemoryCache – start
if (memCache.Contains("tag"))
{
memCache.Remove("tag");
}
//This is to remove the MemoryCache – end
[/csharp]
We have done everything!. That’s fantastic right? Have a happy coding.
Conclusion
Did I miss anything that you may think which is needed? Did you try Web API yet? Have you ever wanted to do caching in Web API? Could you find this post as useful? I hope you liked this article. Please share me 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.
Kindest Regards
Sibeesh Venu