<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>MemoryCache &#8211; Sibeesh Passion</title>
	<atom:link href="https://sibeeshpassion.com/tag/memorycache/feed/" rel="self" type="application/rss+xml" />
	<link>https://sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 02 Jun 2021 15:14:38 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>MemoryCache &#8211; Sibeesh Passion</title>
	<link>https://sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Caching In Web API</title>
		<link>https://sibeeshpassion.com/caching-in-web-api/</link>
					<comments>https://sibeeshpassion.com/caching-in-web-api/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 24 Mar 2016 00:00:39 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Caching]]></category>
		<category><![CDATA[Caching In Web API]]></category>
		<category><![CDATA[MemoryCache]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11410</guid>

					<description><![CDATA[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 [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>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: <a href="http://sibeeshpassion.com/caching-in-mvc/" target="_blank" rel="noopener">Caching In MVC</a>. We will explain caching with the help of <em>System.Runtime.Caching</em> 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. </p>
<li><a href="http://sibeeshpassion.com/category/mvc/" target="_blank" rel="noopener">MVC Tips, Tricks, Blogs</a></li>
<li><a href="http://sibeeshpassion.com/category/web-api/" target="_blank" rel="noopener">Web API Tips, Tricks, Blogs</a></li>
<p>Now we will go and create our application. I hope you will like this. </p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here.</p>
<li><a href="https://code.msdn.microsoft.com/Caching-In-Web-API-cb40be30" target="_blank" rel="noopener">Caching In Web API</a></li>
<p><strong>Background</strong></p>
<p>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 <em>System.Runtime.Caching.dll</em>, which you need to add as reference. </p>
<p><strong>Create a MVC application</strong></p>
<p>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. </p>
<div id="attachment_11405" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-11405" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png" alt="Empty Template With MVC And Web API Folders" width="650" height="484" class="size-full wp-image-11405" srcset="/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png 650w, /wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206-300x223.png 300w, /wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206-400x298.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11405" class="wp-caption-text">Empty Template With MVC And Web API Folders</p></div>
<p>Once you click OK, a project with MVC like folder structure with core references will be created for you.</p>
<div id="attachment_11362" style="width: 277px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png"><img decoding="async" aria-describedby="caption-attachment-11362" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png" alt="Folder Structure And References For Empty MVC Project" width="267" height="367" class="size-full wp-image-11362" srcset="/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png 267w, /wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project-218x300.png 218w" sizes="(max-width: 267px) 100vw, 267px" /></a><p id="caption-attachment-11362" class="wp-caption-text">Folder Structure And References For Empty MVC Project</p></div>
<p>Once your application is ready, we can add the reference for <em>System.Runtime.Caching</em></p>
<p><strong>Add reference for System.Runtime.Caching</strong></p>
<p>To add the reference, right click on References and click Add reference.</p>
<div id="attachment_11411" style="width: 492px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Add_References_.png"><img decoding="async" aria-describedby="caption-attachment-11411" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Add_References_.png" alt="Add_References" width="482" height="316" class="size-full wp-image-11411" srcset="/wp-content/uploads/2016/03/Add_References_.png 482w, /wp-content/uploads/2016/03/Add_References_-300x197.png 300w, /wp-content/uploads/2016/03/Add_References_-400x262.png 400w" sizes="(max-width: 482px) 100vw, 482px" /></a><p id="caption-attachment-11411" class="wp-caption-text">Add_References</p></div>
<p>Now click on the browse button, and search for <em>System.Runtime.Caching</em></p>
<div id="attachment_11412" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/References_Found_-e1458732611680.png"><img decoding="async" aria-describedby="caption-attachment-11412" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/References_Found_-e1458732611680.png" alt="References_Found_" width="650" height="373" class="size-full wp-image-11412" srcset="/wp-content/uploads/2016/03/References_Found_-e1458732611680.png 650w, /wp-content/uploads/2016/03/References_Found_-e1458732611680-300x172.png 300w, /wp-content/uploads/2016/03/References_Found_-e1458732611680-400x230.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11412" class="wp-caption-text">References_Found_</p></div>
<p>And the click OK, the DLL will be added to your references now. </p>
<p><strong>Using the code</strong></p>
<p>We will set up our database first so that we can create Entity Model for our application later. </p>
<p><strong>Create a database</strong></p>
<p>The following query can be used to create a database in your SQL Server.</p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object:  Database [TrialsDB]<br />
CREATE DATABASE [TrialsDB]<br />
 CONTAINMENT = NONE<br />
 ON  PRIMARY<br />
( NAME = N&#8217;TrialsDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf&#8217; , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )<br />
 LOG ON<br />
( NAME = N&#8217;TrialsDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf&#8217; , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT  GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECOVERY FULL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  READ_WRITE<br />
GO<br />
[/sql]</p>
<p>Now we will create the table we needed. As of now I am going to create the table <em>tblTags </em></p>
<p><strong>Create tables in database</strong></p>
<p>Below is the query to create the table <em>tblTags</em>.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[tblTags]    Script Date: 23-Mar-16 5:01:22 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[tblTags](<br />
	[tagId] [int] IDENTITY(1,1) NOT NULL,<br />
	[tagName] [nvarchar](50) NOT NULL,<br />
	[tagDescription] [nvarchar](max) NULL,<br />
 CONSTRAINT [PK_tblTags] PRIMARY KEY CLUSTERED<br />
(<br />
	[tagId] ASC<br />
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]<br />
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<p>Can we insert some data to the tables now?</p>
<p><strong>Insert data to table</strong></p>
<p>You can use the below query to insert the data to the table <em>tblTags</em></p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>INSERT INTO [dbo].[tblTags]<br />
           ([tagName]<br />
           ,[tagDescription])<br />
     VALUES<br />
           (&lt;tagName, nvarchar(50),&gt;<br />
           ,&lt;tagDescription, nvarchar(max),&gt;)<br />
GO<br />
[/sql] </p>
<p>Next thing we are going to do is creating a ADO.NET Entity Data Model. </p>
<p><strong>Create Entity Data Model</strong></p>
<p>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 <em>Dashboard</em> for our Entity data model name. Now you can see a file with edmx extension have been created.<br />
Now will create our Web API controller. </p>
<p><strong>Create Web API Controller</strong></p>
<p>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.</p>
<div id="attachment_11401" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png"><img decoding="async" aria-describedby="caption-attachment-11401" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png" alt="Web API 2 Controller With Actions Using Entity Framework" width="650" height="448" class="size-full wp-image-11401" srcset="/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png 650w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-300x207.png 300w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-160x110.png 160w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-400x276.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11401" class="wp-caption-text">Web API 2 Controller With Actions Using Entity Framework</p></div>
<p>Now select <em>tblTag (CachingInWebAPI.Models)</em> as our Model class and <em>TrialsDBEntities (CachingInWebAPI.Models)</em> as data context class. </p>
<p>As you can see It has been given the name of our controller as <em>tblTags</em>. Here I am not going to change that, if you wish to change, you can do that.</p>
<p>Now you will be given the following codes in our new Web API controller.</p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Data;<br />
using System.Data.Entity;<br />
using System.Data.Entity.Infrastructure;<br />
using System.Linq;<br />
using System.Net;<br />
using System.Net.Http;<br />
using System.Web.Http;<br />
using System.Web.Http.Description;<br />
using CachingInWebAPI.Models;</p>
<p>namespace CachingInWebAPI.Controllers<br />
{<br />
    public class tblTagsController : ApiController<br />
    {<br />
        private TrialsDBEntities db = new TrialsDBEntities();</p>
<p>        // GET: api/tblTags<br />
        public IQueryable&lt;tblTag&gt; GettblTags()<br />
        {<br />
            return db.tblTags;<br />
        }</p>
<p>        // GET: api/tblTags/5<br />
        [ResponseType(typeof(tblTag))]<br />
        public IHttpActionResult GettblTag(int id)<br />
        {<br />
            tblTag tblTag = db.tblTags.Find(id);<br />
            if (tblTag == null)<br />
            {<br />
                return NotFound();<br />
            }</p>
<p>            return Ok(tblTag);<br />
        }</p>
<p>        // PUT: api/tblTags/5<br />
        [ResponseType(typeof(void))]<br />
        public IHttpActionResult PuttblTag(int id, tblTag tblTag)<br />
        {<br />
            if (!ModelState.IsValid)<br />
            {<br />
                return BadRequest(ModelState);<br />
            }</p>
<p>            if (id != tblTag.tagId)<br />
            {<br />
                return BadRequest();<br />
            }</p>
<p>            db.Entry(tblTag).State = EntityState.Modified;</p>
<p>            try<br />
            {<br />
                db.SaveChanges();<br />
            }<br />
            catch (DbUpdateConcurrencyException)<br />
            {<br />
                if (!tblTagExists(id))<br />
                {<br />
                    return NotFound();<br />
                }<br />
                else<br />
                {<br />
                    throw;<br />
                }<br />
            }</p>
<p>            return StatusCode(HttpStatusCode.NoContent);<br />
        }</p>
<p>        // POST: api/tblTags<br />
        [ResponseType(typeof(tblTag))]<br />
        public IHttpActionResult PosttblTag(tblTag tblTag)<br />
        {<br />
            if (!ModelState.IsValid)<br />
            {<br />
                return BadRequest(ModelState);<br />
            }</p>
<p>            db.tblTags.Add(tblTag);<br />
            db.SaveChanges();</p>
<p>            return CreatedAtRoute(&quot;DefaultApi&quot;, new { id = tblTag.tagId }, tblTag);<br />
        }</p>
<p>        // DELETE: api/tblTags/5<br />
        [ResponseType(typeof(tblTag))]<br />
        public IHttpActionResult DeletetblTag(int id)<br />
        {<br />
            tblTag tblTag = db.tblTags.Find(id);<br />
            if (tblTag == null)<br />
            {<br />
                return NotFound();<br />
            }</p>
<p>            db.tblTags.Remove(tblTag);<br />
            db.SaveChanges();</p>
<p>            return Ok(tblTag);<br />
        }</p>
<p>        protected override void Dispose(bool disposing)<br />
        {<br />
            if (disposing)<br />
            {<br />
                db.Dispose();<br />
            }<br />
            base.Dispose(disposing);<br />
        }</p>
<p>        private bool tblTagExists(int id)<br />
        {<br />
            return db.tblTags.Count(e =&gt; e.tagId == id) &gt; 0;<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>As we are not going to use only read operation, you can remove other functionalities and keep only <em>Get </em>methods for now.</p>
<p>[csharp]<br />
 // GET: api/tblTags<br />
        public IQueryable&lt;tblTag&gt; GettblTags()<br />
        {<br />
            return db.tblTags;<br />
        }<br />
[/csharp]</p>
<p>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 <em>http://localhost:4832/api/tblTags</em>. Here <em>tblTags</em> is our Web API controller name. I hope you get the data as a result.</p>
<div id="attachment_11413" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Result-e1458733092316.png"><img decoding="async" aria-describedby="caption-attachment-11413" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Result-e1458733092316.png" alt="Web_API_Result" width="650" height="342" class="size-full wp-image-11413" srcset="/wp-content/uploads/2016/03/Web_API_Result-e1458733092316.png 650w, /wp-content/uploads/2016/03/Web_API_Result-e1458733092316-300x158.png 300w, /wp-content/uploads/2016/03/Web_API_Result-e1458733092316-600x315.png 600w, /wp-content/uploads/2016/03/Web_API_Result-e1458733092316-400x210.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11413" class="wp-caption-text">Web_API_Result</p></div>
<p>Now we will start testing our caching. For that please import the namespace <em>System.Runtime.Caching;</em></p>
<p>[csharp]<br />
using System.Runtime.Caching;<br />
[/csharp]</p>
<p>Next we will create an instance of <em>MemoryCache </em>class.</p>
<div id="attachment_11415" style="width: 664px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Tooltip_.png"><img decoding="async" aria-describedby="caption-attachment-11415" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Tooltip_.png" alt="MemoryCache_Tooltip_" width="654" height="102" class="size-full wp-image-11415" srcset="/wp-content/uploads/2016/03/MemoryCache_Tooltip_.png 654w, /wp-content/uploads/2016/03/MemoryCache_Tooltip_-300x47.png 300w, /wp-content/uploads/2016/03/MemoryCache_Tooltip_-400x62.png 400w" sizes="(max-width: 654px) 100vw, 654px" /></a><p id="caption-attachment-11415" class="wp-caption-text">MemoryCache_Tooltip_</p></div>
<p>As you can see there are four possible settings we can set in <em>MemoryCache </em> class.</p>
<div id="attachment_11416" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751.png"><img decoding="async" aria-describedby="caption-attachment-11416" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751.png" alt="MemoryCache_Settings" width="650" height="123" class="size-full wp-image-11416" srcset="/wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751.png 650w, /wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751-300x57.png 300w, /wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751-400x76.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11416" class="wp-caption-text">MemoryCache_Settings</p></div>
<p>Now we can add MemoryCache as follows. </p>
<p>[csharp]<br />
public IQueryable&lt;tblTag&gt; GettblTags()<br />
        {<br />
            var ca = db.tblTags;<br />
            memCache.Add(&quot;tag&quot;, ca, DateTimeOffset.UtcNow.AddMinutes(5));<br />
            return db.tblTags;<br />
        }<br />
[/csharp]</p>
<div id="attachment_11417" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183.png"><img decoding="async" aria-describedby="caption-attachment-11417" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183.png" alt="MemoryCache_Add" width="650" height="70" class="size-full wp-image-11417" srcset="/wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183.png 650w, /wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183-300x32.png 300w, /wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183-400x43.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11417" class="wp-caption-text">MemoryCache_Add</p></div>
<p>Here &#8220;tag&#8221; is my key and &#8220;ca&#8221; is my values and DateTimeOffset.UtcNow.AddMinutes(5) is for setting the cache for five minutes from now. </p>
<p>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. </p>
<p>[csharp]<br />
var res = memCache.Get(&quot;tag&quot;);<br />
            if (res != null)<br />
            {<br />
                return res;<br />
            }<br />
            else {<br />
                var ca = db.tblTags;<br />
                memCache.Add(&quot;tag&quot;, ca, DateTimeOffset.UtcNow.AddMinutes(5));<br />
                return db.tblTags;<br />
            }<br />
[/csharp]</p>
<p>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 <em>http://localhost:4832/api/tblTags</em>. </p>
<div id="attachment_11418" style="width: 634px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Cache_Value_Null.png"><img decoding="async" aria-describedby="caption-attachment-11418" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Cache_Value_Null.png" alt="Cache_Value_Null" width="624" height="215" class="size-full wp-image-11418" srcset="/wp-content/uploads/2016/03/Cache_Value_Null.png 624w, /wp-content/uploads/2016/03/Cache_Value_Null-300x103.png 300w, /wp-content/uploads/2016/03/Cache_Value_Null-620x215.png 620w, /wp-content/uploads/2016/03/Cache_Value_Null-400x138.png 400w" sizes="(max-width: 624px) 100vw, 624px" /></a><p id="caption-attachment-11418" class="wp-caption-text">Cache_Value_Null</p></div>
<p>You can see that we are setting the value to memCache as the <em>memCache.Get(&#8220;tag&#8221;)</em> is null. </p>
<div id="attachment_11419" style="width: 606px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Cache_Value_Not_Null.png"><img decoding="async" aria-describedby="caption-attachment-11419" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Cache_Value_Not_Null.png" alt="Cache_Value_Not_Null" width="596" height="215" class="size-full wp-image-11419" srcset="/wp-content/uploads/2016/03/Cache_Value_Not_Null.png 596w, /wp-content/uploads/2016/03/Cache_Value_Not_Null-300x108.png 300w, /wp-content/uploads/2016/03/Cache_Value_Not_Null-400x144.png 400w" sizes="(max-width: 596px) 100vw, 596px" /></a><p id="caption-attachment-11419" class="wp-caption-text">Cache_Value_Not_Null</p></div>
<p>So we just tried to load the same Web API URL within five minutes, so we gets values from <em>memCache.Get(&#8220;tag&#8221;)</em>. Sounds good?</p>
<p>There is an option to remove our cache too, we will see that now. We will use the <em>Remove</em> function for the same. First we will check whether the key is available in the <em>MemoryCache</em>, if it is available we will remove that.</p>
<p>[csharp]<br />
//This is to remove the MemoryCache &#8211; start<br />
                if (memCache.Contains(&quot;tag&quot;))<br />
                {<br />
                    memCache.Remove(&quot;tag&quot;);<br />
                }<br />
                //This is to remove the MemoryCache &#8211; end<br />
[/csharp]</p>
<div id="attachment_11420" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814.png"><img decoding="async" aria-describedby="caption-attachment-11420" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814.png" alt="MemoryCache_Remove" width="650" height="299" class="size-full wp-image-11420" srcset="/wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814.png 650w, /wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814-300x138.png 300w, /wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814-400x184.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11420" class="wp-caption-text">MemoryCache_Remove</p></div>
<p>We have done everything!. That&#8217;s fantastic right? Have a happy coding.</p>
<p><strong>Conclusion</strong></p>
<p>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.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;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.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/caching-in-web-api/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
	</channel>
</rss>
