Caching is a crucial technique for improving the performance of ASP.NET Core Web APIs. In this example, I'll walk you through implementing response caching, distributed caching using Redis, and in-memory caching in an ASP.NET Core Web API.
Step 1. Create a new ASP.NET Core Web API project using Visual Studio or the .NET CLI
Create a new Web API project using visual studio or using a command line interface.
Step 2. Install the required NuGet packages for caching
Using NuGet Package Manager Console:
Install-Package Microsoft.Extensions.Caching.Memory
Install-Package Microsoft.Extensions.Caching.StackExchangeRedis
Using .NET CLI
dotnet add package Microsoft.Extensions.Caching.Memory
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
Step 3. Configure caching services in the Startup.cs file
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
Author: Sardar Mudassar Ali Khan
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// Add memory caching
services.AddMemoryCache();
// Add distributed caching using Redis
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379"; // Here You Can Use Your Own Radis Cache
Server
configuration
options.InstanceName = "SampleApp:";
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Step 4. Implement caching in your controllers
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using System;
Author: Sardar Mudassar Ali Khan
[ApiController]
[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
private readonly IMemoryCache _memoryCache;
private readonly IDistributedCache _distributedCache;
public ValuesController(IMemoryCache memoryCache, IDistributedCache distributedCache)
{
_memoryCache = memoryCache;
_distributedCache = distributedCache;
}
[HttpGet("memory")]
[ResponseCache(Duration = 60)] // Response caching for 60 seconds
public IActionResult GetValueFromMemoryCache()
{
// Check if value exists in memory cache
if (_memoryCache.TryGetValue("cachedValue", out string value))
{
return Ok(value);
}
// Cache the value in memory
value = "Value from memory cache";
_memoryCache.Set("cachedValue", value, TimeSpan.FromSeconds(30));
return Ok(value);
}
[HttpGet("distributed")]
public IActionResult GetValueFromDistributedCache()
{
// Check if value exists in distributed cache
byte[] cachedBytes = _distributedCache.Get("cachedBytes");
if (cachedBytes != null)
{
string value = System.Text.Encoding.UTF8.GetString(cachedBytes);
return Ok(value);
}
// Cache the value in distributed cache
string newValue = "Value from distributed cache";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(newValue);
DistributedCacheEntryOptions options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60) // Cache for 60 seconds
};
_distributedCache.Set("cachedBytes", bytes, options);
return Ok(newValue);
}
}
Join the conversation! Your thoughts help the community grow.