Get started with the Redis Output Caching integration

Redis logo

The RedisĀ® output caching integration is used to register an ASP.NET Core Output Caching provider backed by a Redis server with the docker.io/library/redis container image.

In this introduction, you'll see how to install and use the Aspire Redis Output Caching integrations in a simple configuration. If you already have this knowledge, see Redis Output Caching hosting integration for full reference details.

Note

To follow this guide, you must have created an Aspire solution to work with. To learn how to do that, see Build your first Aspire app.

Set up hosting integration

To begin, install the Aspire Redis hosting integration in your Aspire AppHost project:

Install the NuGet package
dotnet add package Aspire.Hosting.Redis

Next, in the AppHost project, create instances of Redis resources and pass them to the consuming client projects:

var builder = DistributedApplication.CreateBuilder(args);
  
var cache = builder.AddRedis("cache");
  
var myService = builder.AddProject<Projects.ExampleProject>()
                       .WithReference(cache);
  
builder.Build().Run();

When Aspire adds a container image to the AppHost, it creates a new Redis instance on your local machine.

Tip

If you'd rather connect to an existing Redis instance, call AsExisting instead.

Set up client integration

To get started with the Redis output caching integration, install the package:

Install the NuGet package
dotnet add package Aspire.StackExchange.Redis.OutputCaching

In the Program.cs file of your client-consuming project, call the AddRedisOutputCache extension method to register the required services for output caching:

builder.AddRedisOutputCache(connectionName: "cache");

Tip

The connectionName parameter must match the name used when adding the Redis resource in the AppHost project.

Add the middleware to the request processing pipeline by calling UseOutputCache:

var app = builder.Build();
  
app.UseOutputCache();

For minimal API apps, configure an endpoint to do caching by calling CacheOutput, or by applying the OutputCacheAttribute:

app.MapGet("/cached", () => "Hello world!")
   .CacheOutput();
  
app.MapGet(
    "/attribute",
    [OutputCache] () => "Hello world!");

For apps with controllers, apply the [OutputCache] attribute to the action method. For Razor Pages apps, apply the attribute to the Razor page class.

See also

[!TIP] Registered trademark Redis is a registered trademark of Redis Ltd. Any rights therein are reserved to Redis Ltd. Any use by Microsoft is for referential purposes only and does not indicate any sponsorship, endorsement or affiliation between Redis and Microsoft.