|
| 1 | +--- |
| 2 | +title: ASP.NET Core output cache provider for Azure Cache for Redis |
| 3 | +description: Use the Redis Output Cache Provider to cache ASP.NET Core page output out of process by using Azure Cache for Redis. |
| 4 | +author: flang-msft |
| 5 | +ms.author: cawa |
| 6 | +ms.service: cache |
| 7 | +ms.devlang: csharp |
| 8 | +ms.custom: devx-track-csharp |
| 9 | +ms.topic: how-to |
| 10 | +ms.date: 06/14/2024 |
| 11 | + |
| 12 | +#customer intent: As a cloud developer, I want to understand core output caching via Azure Cache for Redis so that I can implement it for storing page output. |
| 13 | +--- |
| 14 | + |
| 15 | +# ASP.NET Core Output Cache Provider for Azure Cache for Redis |
| 16 | + |
| 17 | +This article explains how to configure Redis output caching middleware in an ASP.NET Core app. The output caching middleware enables caching of HTTP responses. The benefits of using output caching include: |
| 18 | + |
| 19 | +- Saving web server resource utilization from repeatedly generating HTTP responses and rendering HTML webpages. |
| 20 | +- Improving web request performance by reducing dependency calls. |
| 21 | + |
| 22 | +The benefits of using Azure Cache for Redis as your output cache include: |
| 23 | + |
| 24 | +- Saving web server memory resource utilization by storing cached content in an external Redis database. |
| 25 | +- Improving web application resiliency by persisting cached content in an external Redis database in the scenario of server failover or restart. |
| 26 | + |
| 27 | +You can use the output caching middleware in all types of ASP.NET Core apps: minimal API, web API with controllers, Model-View-Controller (MVC), and Razor Pages. For a detailed walkthrough of output caching syntax and features, see [Output caching middleware in ASP.NET Core](/aspnet/core/performance/caching/output). |
| 28 | + |
| 29 | +## Prerequisites |
| 30 | + |
| 31 | +- [Download](https://dotnet.microsoft.com/download/dotnet/8.0) and install .NET 8 SDK or later. |
| 32 | +- [Download](https://code.visualstudio.com/download) and install Visual Studio Code. |
| 33 | +- Create an Azure Cache for Redis instance. For more information, see: |
| 34 | + - [Quickstart: Create an open-source Redis cache](./quickstart-create-redis.md) |
| 35 | + - [Quickstart: Create a Redis Enterprise cache](./quickstart-create-redis-enterprise.md) |
| 36 | + |
| 37 | +For an end-to-end application that uses Redis output caching, see [.NET 8 Web Application with Redis Output Caching and Azure OpenAI](https://github.com/Azure-Samples/azure-cache-redis-samples/tree/main/tutorial/output-cache-open-ai). |
| 38 | + |
| 39 | +## Add Redis output caching middleware to an empty ASP.NET core web application |
| 40 | + |
| 41 | +Here's the procedure for using Azure Cache for Redis as the output caching middleware in an ASP.NET Core app. The output caching middleware enables caching of HTTP responses as page output. |
| 42 | + |
| 43 | +### Create an empty ASP.NET core web application |
| 44 | + |
| 45 | +Open a command prompt. Use the .NET command line to create an empty ASP.NET core web application: |
| 46 | + |
| 47 | +```cmd |
| 48 | +mkdir RedisOutputCache |
| 49 | +cd RedisOutputCache |
| 50 | +dotnet new web |
| 51 | +``` |
| 52 | + |
| 53 | +### Add NuGet packages for Redis output caching |
| 54 | + |
| 55 | +Make sure your command prompt is in the project folder that contains the `*.csproj` file. Install the [Microsoft.AspNetCore.OutputCaching.StackExchangeRedis](https://www.nuget.org/packages/Microsoft.AspNetCore.OutputCaching.StackExchangeRedis) NuGet package: |
| 56 | + |
| 57 | +```cmd |
| 58 | +dotnet add package Microsoft.AspNetCore.OutputCaching.StackExchangeRedis |
| 59 | +``` |
| 60 | + |
| 61 | +### Add Redis output caching middleware in the web application's startup code |
| 62 | + |
| 63 | +1. Use the command prompt to open the project directory in Visual Studio Code: |
| 64 | + |
| 65 | + ```cmd |
| 66 | + code . |
| 67 | + ``` |
| 68 | +
|
| 69 | + If you're prompted, select **Yes I trust the author** to proceed. |
| 70 | +
|
| 71 | +1. Open the _Program.cs_ file. |
| 72 | +
|
| 73 | +1. Add the `AddStackExchangeRedisOutputCache()`, `AddOutputCache()`, and `UseOutputCache()` function calls: |
| 74 | +
|
| 75 | + ```csharp |
| 76 | + var builder = WebApplication.CreateBuilder(args); |
| 77 | +
|
| 78 | + // add Redis Output Cache Middleware service |
| 79 | + builder.Services.AddStackExchangeRedisOutputCache(options => { |
| 80 | + options.Configuration = builder.Configuration["RedisCacheConnection"]; |
| 81 | + }); |
| 82 | + builder.Services.AddOutputCache(options => { |
| 83 | + // optional: named output-cache profiles |
| 84 | + }); |
| 85 | +
|
| 86 | +
|
| 87 | + var app = builder.Build(); |
| 88 | +
|
| 89 | + app.MapGet("/", () => "Hello World!"); |
| 90 | +
|
| 91 | + // use Redis Output Caching Middleware service |
| 92 | + app.UseOutputCache(); |
| 93 | +
|
| 94 | + app.Run(); |
| 95 | +
|
| 96 | + ``` |
| 97 | +
|
| 98 | +1. Save the _Program.cs_ file. Make sure the application builds with no errors in the command prompt: |
| 99 | +
|
| 100 | + ```cmd |
| 101 | + dotnet build |
| 102 | + ``` |
| 103 | +
|
| 104 | +### Configure one endpoint or page |
| 105 | +
|
| 106 | +1. Add the cached endpoint under `app.MetGet()`: |
| 107 | +
|
| 108 | + ```csharp |
| 109 | + app.MapGet("/", () => "Hello World!"); |
| 110 | + |
| 111 | + //Added for caching HTTP response of one end point |
| 112 | + app.MapGet("/cached",()=> "Hello Redis Output Cache" + DateTime.Now).CacheOutput(); |
| 113 | + ``` |
| 114 | +
|
| 115 | +1. Save the _Program.cs_ file. Make sure the application builds with no errors in the command prompt: |
| 116 | +
|
| 117 | + ```cmd |
| 118 | + dotnet build |
| 119 | + ``` |
| 120 | +
|
| 121 | +### Configure the Redis Cache connection |
| 122 | +
|
| 123 | +It's a security best practice to avoid storing passwords in clear text in source-controlled code files. ASP.NET Core provides [user secrets management](/aspnet/core/security/app-secrets) to help ensure that secrets, such as connection strings, are saved and accessed securely. Use this feature to manage the Azure Cache for Redis connection strings. |
| 124 | +
|
| 125 | +1. Enable the storage of secrets by using the Azure CLI: |
| 126 | +
|
| 127 | + ```cli |
| 128 | + dotnet user-secrets init |
| 129 | + ``` |
| 130 | +
|
| 131 | +1. Obtain the Azure Cache for Redis connection strings by using the Azure portal. |
| 132 | +
|
| 133 | + You can find the connection string for open source Redis tiers by selecting **Authentication** on the **Resource** menu. Here's an example string: `<Azure_redis_name>.redis.cache.windows.net:6380,password=<Azure_redis_primary_accesskey>,ssl=True,abortConnect=False`. |
| 134 | +
|
| 135 | + You can find the access keys for Redis Enterprise by selecting **Access keys** on the **Resource** menu. The connection string can be derived with other Redis information from the **Overview** section of the **Resource** menu. Here's an example string: `<Azure_redis_name>.<Azure_region>.redisenterprise.cache.azure.net:10000,password=<Azure_redis_primary_accesskey>,ssl=True,abortConnect=False`. |
| 136 | +
|
| 137 | +1. Set the Redis connection for the web application by using the Azure CLI: |
| 138 | +
|
| 139 | + ```cli |
| 140 | + dotnet user-secrets set RedisCacheConnection <Azure_Redis_ConnectionString> |
| 141 | + ``` |
| 142 | +
|
| 143 | +1. Run your application: |
| 144 | +
|
| 145 | + ```cli |
| 146 | + dotnet build |
| 147 | + dotnet run |
| 148 | + ``` |
| 149 | +
|
| 150 | + The command prompt displays progress: |
| 151 | +
|
| 152 | + ```cmd |
| 153 | + Building... |
| 154 | + info: Microsoft.Hosting.Lifetime[14] |
| 155 | + Now listening on: http://localhost:5063 |
| 156 | + info: Microsoft.Hosting.Lifetime[0] |
| 157 | + Application started. Press Ctrl+C to shut down. |
| 158 | + ... |
| 159 | + ``` |
| 160 | +
|
| 161 | +### Verify that the Redis output cache is working |
| 162 | +
|
| 163 | +1. Browse to the local host URL. Here's an example: `http://localhost:5063/cached`. |
| 164 | +
|
| 165 | +1. Observe if the current time is being displayed. Refreshing the browser doesn't change the time because the content is cached. The `/cached` endpoint might display text like the following example: |
| 166 | +
|
| 167 | + ```cmd |
| 168 | + Hello Redis Output Cache5/27/2024 8:31:35 PM |
| 169 | + ``` |
| 170 | +
|
| 171 | +## Related content |
| 172 | +
|
| 173 | +- [ASP.NET Output Cache Provider for Azure Cache for Redis](cache-aspnet-output-cache-provider.md) |
| 174 | +- [Output caching](/aspnet/core/performance/caching/overview#output-caching) |
0 commit comments