|
| 1 | +--- |
| 2 | +title: Create an ASP.NET web app with an Azure Managed Redis cache |
| 3 | +description: In this quickstart, you learn how to create an ASP.NET Core web app with an Azure Managed Redis cache. |
| 4 | +ms.date: 01/30/2026 |
| 5 | +ms.topic: quickstart |
| 6 | +ms.devlang: csharp |
| 7 | +zone_pivot_groups: redis-type |
| 8 | +appliesto: |
| 9 | + - ✅ Azure Managed Redis |
| 10 | +ai-usage: ai-assisted |
| 11 | +# Customer intent: As an ASP.NET developer, new to Azure Managed Redis, I want to create a new .NET app that uses Azure Managed Redis. |
| 12 | +--- |
| 13 | + |
| 14 | +# Azure Managed Redis sample - ASP.NET Core Web API |
| 15 | + |
| 16 | +This sample shows how to connect an ASP.NET Core Web API to Azure Managed Redis by using Microsoft Entra ID authentication with the `DefaultAzureCredential` flow. The application avoids traditional connection string-based authentication in favor of token-based, Microsoft Entra ID access, which aligns with modern security best practices. |
| 17 | + |
| 18 | +The application is a minimal ASP.NET Core 8.0 Web API that: |
| 19 | + |
| 20 | +1. Establishes a secure, authenticated connection to Azure Managed Redis at startup. |
| 21 | +1. Exposes a simple REST endpoint that reads and writes data to the cache. |
| 22 | +1. Demonstrates proper Redis connection lifecycle management by using dependency injection. |
| 23 | + |
| 24 | +## Skip to the code on GitHub |
| 25 | + |
| 26 | +Clone the [Microsoft.Azure.StackExchangeRedis](https://github.com/Azure/Microsoft.Azure.StackExchangeRedis/tree/main/sample.aspnet) repo on GitHub. |
| 27 | + |
| 28 | +## Prerequisites |
| 29 | + |
| 30 | +- [.NET 8.0 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). |
| 31 | +- An **Azure Managed Redis** instance provisioned in your Azure subscription. |
| 32 | +- Your Azure user or service principal must be added as a Redis user on the cache. In the Azure portal, go to **Authentication** on the Resource menu, select **User or service principal**, and add your identity. |
| 33 | +- [Azure CLI](/cli/azure/install-azure-cli?view=azure-cli-latest) for local development authentication. |
| 34 | + |
| 35 | +## Required NuGet Packages |
| 36 | + |
| 37 | +| Package | Purpose | |
| 38 | +| --------- | --------- | |
| 39 | +| `Microsoft.Azure.StackExchangeRedis` | Extension methods for StackExchange.Redis that enable Microsoft Entra ID token-based authentication to Azure Managed Redis | |
| 40 | +| `StackExchange.Redis` | The underlying Redis client library for .NET | |
| 41 | +| `Azure.Identity` | Provides `DefaultAzureCredential` and other credential types for authenticating with Azure services | |
| 42 | +| `Swashbuckle.AspNetCore` | Swagger/OpenAPI support for API documentation and testing | |
| 43 | + |
| 44 | +Install the primary package: |
| 45 | + |
| 46 | +```bash |
| 47 | +dotnet add package Microsoft.Azure.StackExchangeRedis |
| 48 | +``` |
| 49 | + |
| 50 | +This package brings in `StackExchange.Redis` and `Azure.Identity` as dependencies. |
| 51 | + |
| 52 | +## Configuration |
| 53 | + |
| 54 | +The application reads the Redis endpoint from configuration. Update `appsettings.Development.json`: |
| 55 | + |
| 56 | +```json |
| 57 | +{ |
| 58 | + "Redis": { |
| 59 | + "Endpoint": "<your-redis-name>.<region>.redis.azure.net:10000" |
| 60 | + } |
| 61 | +} |
| 62 | +``` |
| 63 | + |
| 64 | +> [!NOTE] |
| 65 | +> Azure Managed Redis uses port `10000` by default. The endpoint format follows `<cache-name>.<region>.redis.azure.net:10000`. |
| 66 | +
|
| 67 | +## Authentication Flow |
| 68 | + |
| 69 | +### Local Development |
| 70 | + |
| 71 | +Before running the application locally, authenticate with Azure: |
| 72 | + |
| 73 | +```bash |
| 74 | +az login |
| 75 | +``` |
| 76 | + |
| 77 | +The `DefaultAzureCredential` automatically picks up your Azure CLI credentials and uses them to get an access token for the Redis resource. This approach eliminates the need to manage or rotate secrets locally. |
| 78 | + |
| 79 | +### Production environments |
| 80 | + |
| 81 | +In Azure-hosted environments such as App Service, Container Apps, and AKS, `DefaultAzureCredential` uses: |
| 82 | + |
| 83 | +- **Managed Identity** - system-assigned or user-assigned |
| 84 | +- **Workload Identity** - for Kubernetes scenarios |
| 85 | +- **Environment variables** - for service principal authentication |
| 86 | + |
| 87 | +You don't need to change your code. The same `DefaultAzureCredential` seamlessly adapts to the environment. |
| 88 | + |
| 89 | +## Architecture |
| 90 | + |
| 91 | +### Redis service (`Services/Redis.cs`) |
| 92 | + |
| 93 | +The `Redis` class manages the connection lifecycle: |
| 94 | + |
| 95 | +```csharp |
| 96 | +var options = new ConfigurationOptions() |
| 97 | +{ |
| 98 | + EndPoints = { endpoint }, |
| 99 | + LoggerFactory = _loggerFactory, |
| 100 | +}; |
| 101 | + |
| 102 | +await options.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential()); |
| 103 | + |
| 104 | +_connection = await ConnectionMultiplexer.ConnectAsync(options); |
| 105 | +``` |
| 106 | + |
| 107 | +Key points: |
| 108 | + |
| 109 | +- `ConfigureForAzureWithTokenCredentialAsync` is an extension method from `Microsoft.Azure.StackExchangeRedis` that sets up token-based authentication |
| 110 | +- `DefaultAzureCredential` automatically handles token acquisition and refresh |
| 111 | +- The app establishes the connection once at startup and shares it across requests |
| 112 | + |
| 113 | +### Dependency injection (`Program.cs`) |
| 114 | + |
| 115 | +The app registers the Redis service as a singleton and initializes it during startup: |
| 116 | + |
| 117 | +```csharp |
| 118 | +builder.Services.AddSingleton<Redis>(); |
| 119 | + |
| 120 | +// Initialize Redis connection |
| 121 | +using (var scope = app.Services.CreateScope()) |
| 122 | +{ |
| 123 | + var redis = scope.ServiceProvider.GetRequiredService<Redis>(); |
| 124 | + var endpoint = app.Configuration.GetValue<string>("Redis:Endpoint"); |
| 125 | + await redis.ConnectAsync(endpoint); |
| 126 | +} |
| 127 | +``` |
| 128 | + |
| 129 | +### API Controller (`Controllers/SampleController.cs`) |
| 130 | + |
| 131 | +The controller injects the `Redis` service and demonstrates basic cache operations: |
| 132 | + |
| 133 | +- **GET `/Sample`**: Reads the previous visit timestamp from the cache and updates it with the current time |
| 134 | + |
| 135 | +## Running the application |
| 136 | + |
| 137 | +1. Ensure you're authenticated: |
| 138 | + |
| 139 | + ```bash |
| 140 | + az login |
| 141 | + ``` |
| 142 | + |
| 143 | +1. Update the Redis endpoint in `appsettings.Development.json`. |
| 144 | + |
| 145 | +1. Run the application: |
| 146 | + |
| 147 | + ```bash |
| 148 | + dotnet run |
| 149 | + ``` |
| 150 | + |
| 151 | +1. Navigate to `https://localhost:<port>/swagger` to access the Swagger UI. |
| 152 | + |
| 153 | +## Expected output |
| 154 | + |
| 155 | +When invoking the `GET /Sample` endpoint: |
| 156 | + |
| 157 | +**First request:** |
| 158 | + |
| 159 | +```bash |
| 160 | +Previous visit was at: |
| 161 | +(Empty value since no previous visit exists) |
| 162 | +``` |
| 163 | + |
| 164 | +```bash |
| 165 | +**Subsequent requests:** |
| 166 | +Previous visit was at: 2026-01-30T14:23:45 |
| 167 | +(Returns the ISO 8601 formatted timestamp of the previous request) |
| 168 | +``` |
| 169 | + |
| 170 | +The console logs display: |
| 171 | + |
| 172 | +```bash |
| 173 | +info: Microsoft.Azure.StackExchangeRedis.Sample.AspNet.Controllers.SampleController |
| 174 | + Handled GET request. Previous visit time: 2026-01-30T14:23:45 |
| 175 | +``` |
| 176 | + |
| 177 | +## Key implementation details |
| 178 | + |
| 179 | +- **Token refresh**: The `Microsoft.Azure.StackExchangeRedis` library automatically refreshes tokens before they expire, so you don't need to handle refresh manually. |
| 180 | + |
| 181 | +- **Connection resilience**: The `ConnectionMultiplexer` from StackExchange.Redis manages reconnection logic on its own. |
| 182 | + |
| 183 | +- **Resource cleanup**: The `Redis` service implements `IDisposable` to properly close the connection when the application shuts down. |
| 184 | + |
| 185 | +- **Logging integration**: The Redis client works with .NET's `ILoggerFactory` for unified logging output. |
| 186 | + |
| 187 | +## Troubleshooting |
| 188 | + |
| 189 | +| Issue | Resolution | |
| 190 | +| ------- | ------------ | |
| 191 | +| `No connection is available` | Verify the endpoint format and port (`10000`). Make sure the Redis instance is provisioned and accessible. | |
| 192 | +| `AuthenticationFailedException` | Run `az login` to refresh credentials. Verify your identity is added as a Redis user under **Authentication** on the Resource menu. | |
| 193 | +| `Unauthorized` | Ensure your Microsoft Entra ID identity is added as a Redis user on the Azure Managed Redis instance. For more information, see [Use Microsoft Entra ID for cache authentication](entra-for-authentication.md). | |
| 194 | + |
| 195 | +## Related content |
| 196 | + |
| 197 | +- [Microsoft Entra ID authentication for Azure Managed Redis](entra-for-authentication.md) |
| 198 | +- [DefaultAzureCredential overview](/dotnet/azure/sdk/authentication) |
0 commit comments