Wednesday, January 17, 2024

ASP.NET Core 8.0: Output Caching using Redis

With ASP.NET Core 8.0, now you can use Redis as your cache provider when cashing responses. The default is in-memory cache.

In this post, let's see how you can use Redis for output caching.

First, we need to install Microsoft.AspNetCore.OutputCaching.StackExchangeRedis NuGet package.

And then call AddStackExchangeRedisOutputCache to add Redis output caching services to the service collection.

// Add Redis output caching
builder.Services.AddStackExchangeRedisOutputCache(options =>
{
    options.Configuration =
        builder.Configuration.GetConnectionString("Redis");
});

And that's pretty much it.

The complete code looks like below.

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

// Add Redis output caching services
builder.Services.AddStackExchangeRedisOutputCache(options =>
{
    options.Configuration =
        builder.Configuration.GetConnectionString("Redis");
});
// Add output caching services
builder.Services.AddOutputCache(options =>
{
    options.AddBasePolicy(builder => builder.Cache());
});

WebApplication app = builder.Build();

app.UseHttpsRedirection();

// Add output caching middleware to the request pipeline
app.UseOutputCache();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Mild", "Balmy", "Scorching"
};

app
    .MapGet("/weatherforecast", () =>
    {
        WeatherForecast[] forecast = Enumerable.Range(1, 5)
            .Select(index => new WeatherForecast
            (
                DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                Random.Shared.Next(-20, 55),
                summaries[Random.Shared.Next(summaries.Length)]
            ))
            .ToArray();
        return forecast;
    })
    .CacheOutput(); // enable output caching for this endpoint

app.Run();

internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

And you can see responses are getting cached.

Redis
More read:
   Output caching middleware in ASP.NET Core

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment