This content originally appeared on DEV Community and was authored by Morteza Jangjoo
Tags: dotnet
csharp
redis
webdev
Redis is a super-fast in-memory key-value store. It’s often used for caching, sessions, and real-time apps. In this guide, we’ll learn how to integrate Redis into a .NET Core Web API with a simple example.
Step 1: Run Redis with Docker
docker run --name redis-demo -d -p 6379:6379 redis
Step 2: Add Redis NuGet Package
dotnet add package StackExchange.Redis
Step 3: Configure Redis in Program.cs
using StackExchange.Redis;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
{
var configuration = builder.Configuration.GetConnectionString("Redis");
return ConnectionMultiplexer.Connect(configuration);
});
builder.Services.AddScoped<RedisCacheService>();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Add connection string in appsettings.json
:
{
"ConnectionStrings": {
"Redis": "localhost:6379"
}
}
Step 4: Create Redis Service
RedisCacheService.cs
using StackExchange.Redis;
using System.Text.Json;
public class RedisCacheService
{
private readonly IDatabase _db;
public RedisCacheService(IConnectionMultiplexer redis)
{
_db = redis.GetDatabase();
}
public async Task SetAsync<T>(string key, T value, TimeSpan? expiry = null)
{
var json = JsonSerializer.Serialize(value);
await _db.StringSetAsync(key, json, expiry);
}
public async Task<T?> GetAsync<T>(string key)
{
var value = await _db.StringGetAsync(key);
if (value.IsNullOrEmpty) return default;
return JsonSerializer.Deserialize<T>(value!);
}
public async Task RemoveAsync(string key)
{
await _db.KeyDeleteAsync(key);
}
}
Step 5: Use Redis in Controller
Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly RedisCacheService _cache;
public ProductsController(RedisCacheService cache)
{
_cache = cache;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetProduct(int id)
{
string key = $"product:{id}";
var product = await _cache.GetAsync<Product>(key);
if (product != null)
return Ok(product);
// Simulate DB fetch
product = new Product { Id = id, Name = $"Product {id}" };
await _cache.SetAsync(key, product, TimeSpan.FromMinutes(1));
return Ok(product);
}
}
public record Product
{
public int Id { get; set; }
public string Name { get; set; }
}
Step 6: Test It
Run the app:
dotnet run
Now call the API:
GET https://localhost:5001/api/products/1
- First request → loads product from DB (simulated).
- Next request → served instantly from Redis.
Conclusion
Redis + .NET Core = faster apps and better scalability.
Use it for caching, sessions, pub/sub, and real-time apps.
you can get source code from github
I’m Morteza Jangjoo and “Explaining things I wish someone had explained to me”
This content originally appeared on DEV Community and was authored by Morteza Jangjoo