Introduction
Caching is a crucial technique for improving the performance and responsiveness of web applications by storing frequently accessed data in memory. In the ASP.NET Core Web API, you can easily implement an in-memory cache using the IMemoryCache interface provided by the framework. In this article, we'll walk through a complete practical example of implementing and using an in-memory cache in an ASP.NET Core Web API project.
Step 1. Create a New ASP.NET Core Web API Project
First, let's create a new ASP.NET Core Web API project using Visual Studio or the.NET CLI. Open your preferred development environment and run the following command to create a new Web API project:
dotnet new webapi -n InMemoryCacheExample
This command will create a new ASP.NET Core Web API project named InMemoryCacheExample.
Step 2. Add Memory Cache Service
Open the Startup.cs file in your project and add the memory cache service to the services collection in the ConfigureServices method:
Step 3. Create a Sample Data Model and Controller
Let's create a simple data model and a controller to demonstrate caching. Create a new folder named Models in your project and add a class named Product.cs with the following code:
namespace _101InMemoryCacheInAspNetCore.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
Next, create a new controller named ProductsController.cs in the Controllers folder with the following code:
using _101InMemoryCacheInAspNetCore.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
namespace _101InMemoryCacheInAspNetCore.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly IMemoryCache _memoryCache;
public ProductsController(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
[HttpGet("{id}")]
public ActionResult<Product> Get(int id)
{
if (_memoryCache.TryGetValue($"Product_{id}", out Product cachedProduct))
{
return Ok(cachedProduct);
}
else
{
var product = new Product { Id = id, Name = $"Product {id}", Price = 99.99M };
_memoryCache.Set($"Product_{id}", product, TimeSpan.FromMinutes(10));
return Ok(product);
}
}
}
}
In this controller, we inject the IMemoryCache interface into the constructor. The Get method first checks if the product with the specified ID exists in the cache. If found, it returns the cached product. Otherwise, it simulates fetching the product from a data source, stores it in the cache for 10 minutes, and then returns it.
Step 4. Test the Web API
Build and run your ASP.NET Core Web API project. You can use tools like Postman or curl to test the API endpoints.

Kirtesh ShahPosted Jan 24, 2025, 7:18 AM
What is the difference between the IMemoryCache and OutputCache attributes in .Net Core? and when should each be utilized?