Skip to content

Commit 945583d

Browse files
committed
added new file
1 parent 31abcd0 commit 945583d

1 file changed

Lines changed: 196 additions & 0 deletions

File tree

articles/redis/aspnet.md

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
---
2+
title: Create an ASP.NET Core web app with an Azure Redis cache
3+
description: In this quickstart, you learn how to create an ASP.NET Core web app with an Azure 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 Cache for Redis
10+
# Customer intent: As an ASP.NET developer, new to Azure Redis, I want to create a new Node.js app that uses Azure Managed Redis or Azure Cache for Redis.
11+
---
12+
13+
# Azure Managed Redis Sample - ASP.NET Core Web API
14+
15+
This sample demonstrates how to connect an ASP.NET Core Web API to **Azure Managed Redis** using **Microsoft Entra ID authentication** (formerly Azure Active Directory) with the `DefaultAzureCredential` flow. The application avoids traditional connection string-based authentication in favor of token-based, identity-driven access—aligning with modern security best practices.
16+
17+
## Overview
18+
19+
The application is a minimal ASP.NET Core 8.0 Web API that:
20+
21+
1. Establishes a secure, authenticated connection to Azure Managed Redis at startup
22+
2. Exposes a simple REST endpoint that reads and writes data to the cache
23+
3. Demonstrates proper Redis connection lifecycle management with dependency injection
24+
25+
## Prerequisites
26+
27+
- [.NET 8.0 SDK](https://dotnet.microsoft.com/download/dotnet/8.0)
28+
- An **Azure Managed Redis** instance provisioned in your Azure subscription
29+
- Your Azure user or service principal must have the appropriate **Data Access Policy** assigned on the Redis resource (e.g., `Data Owner`, `Data Contributor`, or a custom policy with read/write permissions)
30+
- [Azure CLI](https://docs.microsoft.com/cli/azure/install-azure-cli) for local development authentication
31+
32+
## Required NuGet Packages
33+
34+
| Package | Purpose |
35+
| --------- | --------- |
36+
| `Microsoft.Azure.StackExchangeRedis` | Extension methods for StackExchange.Redis that enable Microsoft Entra ID token-based authentication to Azure Managed Redis |
37+
| `StackExchange.Redis` | The underlying Redis client library for .NET |
38+
| `Azure.Identity` | Provides `DefaultAzureCredential` and other credential types for authenticating with Azure services |
39+
| `Swashbuckle.AspNetCore` | Swagger/OpenAPI support for API documentation and testing |
40+
41+
Install the primary package:
42+
43+
```bash
44+
dotnet add package Microsoft.Azure.StackExchangeRedis
45+
```
46+
47+
This package transitively brings in `StackExchange.Redis` and `Azure.Identity`.
48+
49+
## Configuration
50+
51+
The application reads the Redis endpoint from configuration. Update `appsettings.Development.json`:
52+
53+
```json
54+
{
55+
"Redis": {
56+
"Endpoint": "<your-redis-name>.<region>.redis.azure.net:10000"
57+
}
58+
}
59+
```
60+
61+
> **Note:** Azure Managed Redis uses port `10000` by default. The endpoint format follows `<cache-name>.<region>.redis.azure.net:10000`.
62+
63+
## Authentication Flow
64+
65+
### Local Development
66+
67+
Before running the application locally, authenticate with Azure:
68+
69+
```bash
70+
az login
71+
```
72+
73+
The `DefaultAzureCredential` will automatically pick up your Azure CLI credentials and use them to obtain an access token for the Redis resource. This eliminates the need to manage or rotate secrets locally.
74+
75+
### Production Environments
76+
77+
In Azure-hosted environments (App Service, Container Apps, AKS, etc.), `DefaultAzureCredential` will leverage:
78+
79+
- **Managed Identity** (system-assigned or user-assigned)
80+
- **Workload Identity** (for Kubernetes scenarios)
81+
- **Environment variables** (for service principal authentication)
82+
83+
No code changes are required—the same `DefaultAzureCredential` seamlessly adapts to the environment.
84+
85+
## Architecture
86+
87+
### Redis Service (`Services/Redis.cs`)
88+
89+
The `Redis` class encapsulates the connection lifecycle:
90+
91+
```csharp
92+
var options = new ConfigurationOptions()
93+
{
94+
EndPoints = { endpoint },
95+
LoggerFactory = _loggerFactory,
96+
};
97+
98+
await options.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
99+
100+
_connection = await ConnectionMultiplexer.ConnectAsync(options);
101+
```
102+
103+
Key points:
104+
105+
- `ConfigureForAzureWithTokenCredentialAsync` is the extension method from `Microsoft.Azure.StackExchangeRedis` that configures token-based authentication
106+
- The `DefaultAzureCredential` handles the token acquisition and refresh automatically
107+
- The connection is established once at startup and shared across requests
108+
109+
### Dependency Injection (`Program.cs`)
110+
111+
The Redis service is registered as a singleton and initialized during application startup:
112+
113+
```csharp
114+
builder.Services.AddSingleton<Redis>();
115+
116+
// Initialize Redis connection
117+
using (var scope = app.Services.CreateScope())
118+
{
119+
var redis = scope.ServiceProvider.GetRequiredService<Redis>();
120+
var endpoint = app.Configuration.GetValue<string>("Redis:Endpoint");
121+
await redis.ConnectAsync(endpoint);
122+
}
123+
```
124+
125+
### API Controller (`Controllers/SampleController.cs`)
126+
127+
The controller injects the `Redis` service and demonstrates basic cache operations:
128+
129+
- **GET `/Sample`**: Reads the previous visit timestamp from the cache and updates it with the current time
130+
131+
## Running the Application
132+
133+
1. Ensure you're authenticated:
134+
135+
```bash
136+
az login
137+
```
138+
139+
1. Update the Redis endpoint in `appsettings.Development.json`
140+
141+
1. Run the application:
142+
143+
```bash
144+
dotnet run
145+
```
146+
147+
1. Navigate to `https://localhost:<port>/swagger` to access the Swagger UI
148+
149+
## Expected Output
150+
151+
When invoking the `GET /Sample` endpoint:
152+
153+
**First request:**
154+
155+
```bash
156+
Previous visit was at:
157+
(Empty value since no previous visit exists)
158+
```
159+
160+
```bash
161+
**Subsequent requests:**
162+
Previous visit was at: 2026-01-30T14:23:45
163+
(Returns the ISO 8601 formatted timestamp of the previous request)
164+
```
165+
166+
The console logs will display:
167+
168+
```bash
169+
info: Microsoft.Azure.StackExchangeRedis.Sample.AspNet.Controllers.SampleController
170+
Handled GET request. Previous visit time: 2026-01-30T14:23:45
171+
```
172+
173+
## Key Implementation Details
174+
175+
1. **Token Refresh**: The `Microsoft.Azure.StackExchangeRedis` library automatically handles token refresh before expiration—no manual intervention required.
176+
177+
1. **Connection Resilience**: The `ConnectionMultiplexer` from StackExchange.Redis handles reconnection logic internally.
178+
179+
1. **Resource Cleanup**: The `Redis` service implements `IDisposable` to properly close the connection when the application shuts down.
180+
181+
1. **Logging Integration**: The Redis client integrates with .NET's `ILoggerFactory` for unified logging output.
182+
183+
## Troubleshooting
184+
185+
| Issue | Resolution |
186+
| ------- | ------------ |
187+
| `No connection is available` | Verify the endpoint format and port (`10000`). Ensure the Redis instance is provisioned and accessible. |
188+
| `AuthenticationFailedException` | Run `az login` to refresh credentials. Verify your identity has the required Data Access Policy on the Redis resource. |
189+
| `Unauthorized` | Ensure your Microsoft Entra ID identity is assigned a data access role on the Azure Managed Redis instance. |
190+
191+
## Additional Resources
192+
193+
- [Azure Managed Redis documentation](https://learn.microsoft.com/azure/azure-cache-for-redis/)
194+
- [Microsoft Entra ID authentication for Azure Cache for Redis](https://learn.microsoft.com/azure/azure-cache-for-redis/cache-azure-active-directory-for-authentication)
195+
- [DefaultAzureCredential overview](https://learn.microsoft.com/dotnet/azure/sdk/authentication#defaultazurecredential)
196+
- [StackExchange.Redis documentation](https://stackexchange.github.io/StackExchange.Redis/)

0 commit comments

Comments
 (0)