Introduction
Using Azure Cache for Redis or a Content Delivery Network (CDN) can indeed help improve API response times and reduce the load on your server. In this example, I'll provide code snippets and steps to integrate Azure Cache for Redis and Azure CDN into an ASP.NET Core Web API application.
Note. Before proceeding, make sure you have an Azure account and have created a Redis Cache instance and a CDN profile in your Azure portal.
Create an ASP.NET Core Web API Project
Start by creating a new ASP.NET Core Web API project in Visual Studio or using the command line.
Add Required NuGet Packages
Install the necessary NuGet packages for Azure Cache for Redis and Azure CDN.
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
Configure Redis Cache
In your Startup.cs file, configure Redis Cache as a distributed cache provider in the ConfigureServices method.
using Microsoft.Extensions.Caching.StackExchangeRedis;
Author: Sardar Mudassar Ali Khan
public void ConfigureServices(IServiceCollection services)
{
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "your-redis-connection-string"; // Replace with your Redis connection string
options.InstanceName = "SampleInstance";
});
}
Cache API Responses
In your API controllers, cache the responses using the IDistributedCache interface.
using Microsoft.Extensions.Caching.Distributed;
Author: Sardar Mudassar Ali Khan
[ApiController]
[Route("api/[controller]")]
public class SampleController: ControllerBase
{
private readonly IDistributedCache _cache;
public SampleController(IDistributedCache cache)
{
_cache = cache;
}
[HttpGet("cached-data")]
public async Task<IActionResult> GetCachedData()
{
var cacheKey = "cached-data-key";
var cachedData = await _cache.GetStringAsync(cacheKey);
if (cachedData != null)
{
return Ok(cachedData);
}
else
{
var data = GetDataFromDataSource();
await _cache.SetStringAsync(cacheKey, data, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(15)
});
return Ok(data);
}
}
}
Get the Data From GetDataFromDataSource Method
Author: Sardar Mudassar Ali Khan
private string GetDataFromDataSource()
{
using (var connection = new SqlConnection("YourConnectionString"))
{
connection.Open();
using (var command = new SqlCommand("SELECT SomeColumn FROM YourTable", connection))
{
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
// Assuming "SomeColumn" is the column from your data source
return reader["SomeColumn"].ToString();
}
}
}
}
return "Data not available";
}
Join the conversation! Your thoughts help the community grow.