Featured Post

How to Set Up Redis in a .NET Core Web API

How to Set Up Redis in a .NET Core Web API

Redis is a high-performance in-memory data store that can be used as a database, cache, or message broker. In this blog post, we will walk through how to set up Redis in a .NET Core Web API application. We will cover installing required packages, configuring Redis, and using it in your application via both low-level and high-level abstractions. We’ll also show you how to set it up on Windows using MSI, Docker, or WSL.


1. Install Required Packages

First, we need to add the necessary NuGet packages to our project:

Core Redis Client:

dotnet add package StackExchange.Redis

Distributed Cache Integration (Optional):

dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

2. Configure Redis Connection

appsettings.json

Add your Redis connection string to appsettings.json:

{
  "Redis": {
    "ConnectionString": "localhost:6379"
  }
}

Replace localhost:6379 with your actual Redis server configuration.

Register in Startup (for .NET 5/6 or earlier)

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        var redisConnectionString = Configuration["Redis:ConnectionString"];

        services.AddSingleton<IConnectionMultiplexer>(
            ConnectionMultiplexer.Connect(redisConnectionString));

        services.AddStackExchangeRedisCache(options =>
        {
            options.Configuration = redisConnectionString;
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Register in Program.cs (for .NET 6 Minimal APIs)

var builder = WebApplication.CreateBuilder(args);

var redisConfiguration = builder.Configuration["Redis:ConnectionString"];

builder.Services.AddSingleton<IConnectionMultiplexer>(
    ConnectionMultiplexer.Connect(redisConfiguration));

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = redisConfiguration;
});

builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();
app.Run();

3. Using Redis in Controllers

a. Low-Level Access with StackExchange.Redis

[ApiController]
[Route("[controller]")]
public class CacheController : ControllerBase
{
    private readonly IConnectionMultiplexer _redis;

    public CacheController(IConnectionMultiplexer redis)
    {
        _redis = redis;
    }

    [HttpGet("get/{key}")]
    public async Task<IActionResult> GetValue(string key)
    {
        var db = _redis.GetDatabase();
        var value = await db.StringGetAsync(key);
        return Ok(value.ToString());
    }

    [HttpPost("set")]
    public async Task<IActionResult> SetValue([FromBody] KeyValuePair<string, string> data)
    {
        var db = _redis.GetDatabase();
        bool wasSet = await db.StringSetAsync(data.Key, data.Value);
        return Ok(new { success = wasSet });
    }
}

b. High-Level Caching with IDistributedCache

[ApiController]
[Route("[controller]")]
public class DistributedCacheController : ControllerBase
{
    private readonly IDistributedCache _cache;

    public DistributedCacheController(IDistributedCache cache)
    {
        _cache = cache;
    }

    [HttpGet("get/{key}")]
    public async Task<IActionResult> GetValue(string key)
    {
        var cachedData = await _cache.GetStringAsync(key);
        if (cachedData == null)
        {
            return NotFound();
        }
        return Ok(cachedData);
    }

    [HttpPost("set")]
    public async Task<IActionResult> SetValue([FromBody] KeyValuePair<string, string> data)
    {
        var options = new DistributedCacheEntryOptions()
            .SetSlidingExpiration(TimeSpan.FromMinutes(30));

        await _cache.SetStringAsync(data.Key, data.Value, options);
        return Ok();
    }
}

4. Installing Redis on Windows

🪟 Option 1: Install via MSI (Unofficial Redis for Windows)

  1. Go to the MicrosoftArchive Redis Releases.

  2. Download the file Redis-x64-3.2.100.msi.

  3. Run the installer and follow the instructions.

  4. After installation, open Command Prompt and start the server:

    redis-server
    
  5. In another terminal, test Redis:

    redis-cli
    

⚠️ This version is outdated and only suitable for development or testing. Use Docker or WSL for more stability.

🐳 Option 2: Use Docker on Windows

Make sure you have Docker Desktop installed. Then run:

docker run --name redis -p 6379:6379 -d redis

🐧 Option 3: Install Redis via WSL (Windows Subsystem for Linux)

  1. Enable WSL and install a Linux distribution like Ubuntu from the Microsoft Store.

  2. Open the terminal and run:

    sudo apt update
    sudo apt install redis-server
    redis-server
    

5. Advanced Features and Considerations

a. Connection Multiplexing

  • IConnectionMultiplexer is thread-safe and should be a singleton.

b. Publish/Subscribe

Redis also supports pub/sub:

var subscriber = _redis.GetSubscriber();
await subscriber.SubscribeAsync("myChannel", (channel, message) => {
    Console.WriteLine($"Message received: {message}");
});

c. Serialization

Use JSON or MessagePack for storing complex objects in Redis.


6. Summary

  • Install StackExchange.Redis and optionally Microsoft.Extensions.Caching.StackExchangeRedis

  • Configure Redis in appsettings.json

  • Register Redis services in your DI container

  • Use IConnectionMultiplexer for low-level access or IDistributedCache for high-level caching

  • On Windows, use MSI for quick setup, or Docker/WSL for a stable dev environment

Redis is a powerful tool that enhances performance and scalability. Integrating it into your .NET Core Web API unlocks faster data access, improved caching, and real-time capabilities through pub/sub.

Happy coding!

Comments