Zum Inhalt springen

Get started with the Redis Output Caching integration

Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.

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.

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

Aspire CLI — Aspire.Hosting.Redis Paket hinzufügen
aspire add redis

Die Aspire CLI ist interaktiv; das passende Suchergebnis wählen, wenn gefragt:

Aspire CLI — Beispielausgabe
Select an integration to add:
> redis (Aspire.Hosting.Redis)
> Other results listed as selectable options...

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

C# — AppHost.cs
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.

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

.NET CLI — Add Aspire.StackExchange.Redis.OutputCaching 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");

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.