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";
}
Configure Azure CDN
Set up your Azure CDN profile and endpoint in the Azure portal. Obtain the CDN endpoint URL.
Integrate CDN into API Responses
Update your API responses to include CDN URLs for assets like images, CSS, or JavaScript files. You can use the CDN URL for these assets instead of serving them directly from your server.
Author: Sardar Mudassar Ali Khan
[ApiController]
[Route("api/[controller]")]
public class SampleController: ControllerBase
{
private readonly IConfiguration _configuration;
public SampleController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpGet("cdn-data")]
public IActionResult GetCDNData()
{
var cdnBaseUrl = _configuration["CdnBaseUrl"]; // Replace with your CDN URL
var data = new
{
message = "Hello from the CDN!",
imageUrl = $"{cdnBaseUrl}/images/sample.jpg",
};
return Ok(data);
}
}
Configure CDN URL
In your appsettings.json or environment variables, configure the CDN URL.
Author: Sardar Mudassar Ali Khan
{
"CdnBaseUrl": "https://azurecacheapp.azureedge.net" // This will be your App
}
Deploy and Test
- Deploy your ASP.NET Core Web API to Azure or your preferred hosting platform, and test the API endpoints. Cached data will be served from Redis Cache, and assets will be served from Azure CDN.
- By following these steps, you can improve API response times by caching data with Azure Cache for Redis and reduce server load by offloading static assets to Azure CDN.
Conclusion
Using Azure Cache for Redis and Azure CDN in your ASP.NET Core Web API can significantly improve API response times and reduce the load on your server. Here's a summary of the key benefits and steps.
- Improved Response Times: Caching frequently requested data in Azure Cache for Redis reduces the need to repeatedly fetch data from the database or other data sources, resulting in faster response times for your API.
- Reduced Server Load: By caching data and offloading static assets (such as images, CSS, and JavaScript) to Azure CDN, you reduce the workload on your API server, making it more scalable and resilient.
Steps
- Create ASP.NET Core Web API: Start by creating a new ASP.NET Core Web API project.
- Add Required NuGet Packages: Install the necessary NuGet packages for Azure Cache for Redis and Azure CDN.
- Configure Redis Cache: Configure Redis Cache as a distributed cache provider in the Startup.cs file.
- Cache API Responses: Cache API responses using the IDistributedCache interface in your API controllers. Use this cache to store and retrieve data from your data source.
- Configure Azure CDN: Set up your Azure CDN profile and endpoint in the Azure portal. Obtain the CDN endpoint URL.
- Integrate CDN into API Responses: Update your API responses to include CDN URLs for static assets like images, CSS, or JavaScript files.
- Configure CDN URL: In your configuration (e.g., appsettings.json), specify the CDN URL.
- Deploy and Test: Deploy your ASP.NET Core Web API to your hosting platform and test the API endpoints. Cached data will be served from Redis Cache, and static assets will be served from Azure CDN.
By following these steps and leveraging Azure Cache for Redis and Azure CDN, you can optimize your API's performance, reduce server load, and deliver a faster and more efficient experience to your users.