Skip to content

Commit f606000

Browse files
committed
More Updates
1 parent 4d55366 commit f606000

File tree

1 file changed

+106
-23
lines changed

1 file changed

+106
-23
lines changed

articles/azure-cache-for-redis/cache-tutorial-appservice-get-started.md

Lines changed: 106 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,9 @@ In this tutorial, you will start with a basic ASP.NET Core Web App and then add
2929

3030
1. Create a new Azure Cache for Redis instance by using the Azure portal or your preferred CLI tool. Use the [quickstart guide](quickstart-create-redis.md) to get started.
3131

32-
For this tutorial, use a Standard C1 cache.
33-
:::image type="content" source="media/cache-tutorial-aks-get-started/cache-new-instance.png" alt-text="Screenshot of creating a Standard C1 cache in the Azure portal":::
34-
3532
1. On the **Advanced** tab, enable Microsoft Entra Authentication.
3633

37-
1. Follow the steps through to create the cache.
34+
1. Follow the steps through to create the cache. Alternately, you can run the following steps on an existing cache with Microsoft Entra Authentication enabled.
3835

3936
1. Once your cache is created, go to the **Data Access Configuration** and click on Add > New Redis User.
4037

@@ -54,9 +51,18 @@ Follow the steps described in the [Azure App Service tutorial](https://learn.mic
5451

5552
1. Open your web application in Visual Studio and right click on the project. Click on the Manage NuGet Packages. Browse and install the latest version of Microsoft.Azure.StackExchangeRedis.
5653

57-
1. Open the Index.cshtml file and append the following code to a button which will write data to your Azure Cache for Redis instance
54+
1. Open the Views/Home/Index.cshtml file and replace with the following code to a button which will write data to your Azure Cache for Redis instance
5855

5956
```html
57+
@{
58+
ViewData["Title"] = "Home Page";
59+
}
60+
61+
<div class="text-center">
62+
<h1 class="display-4">Welcome</h1>
63+
<p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
64+
</div>
65+
6066
<div class="text-center">
6167
<button onclick="UpdateTimeStamp()">Update timestamp</button>
6268
<input type="text" id="timestampTextBox" style="min-width:30%" />
@@ -73,51 +79,128 @@ Follow the steps described in the [Azure App Service tutorial](https://learn.mic
7379
});
7480
}
7581
</script>
82+
7683
```
7784

78-
1. Open the HomeController.cs file and add the following code to handle the click event for the new button you just added.
85+
1. Open the Controllers/HomeController.cs file and replace with the following code to handle the click event for the new button you just added.
86+
7987

8088
```CSharp
81-
[HttpGet]
82-
public async Task<IActionResult> UpdateTimeStamp()
89+
90+
using DemoWebApp.Models;
91+
using Microsoft.AspNetCore.Mvc;
92+
using StackExchange.Redis;
93+
using System.Diagnostics;
94+
95+
namespace DemoWebApp.Controllers
8396
{
84-
await _redisDB.StringSetAsync(key, DateTime.UtcNow.ToString("s"));
85-
return Ok("Last timestamp: " + (await _redisDB.StringGetAsync(key)).ToString());
97+
public class HomeController : Controller
98+
{
99+
private readonly ILogger<HomeController> _logger;
100+
private readonly IDatabase _redisDB;
101+
const string key = "mykey";
102+
103+
public HomeController(ILogger<HomeController> logger, IDatabase redisDB)
104+
{
105+
_logger = logger;
106+
_redisDB = redisDB ?? throw new ArgumentNullException();
107+
}
108+
109+
public IActionResult Index()
110+
{
111+
return View();
112+
}
113+
114+
public IActionResult Privacy()
115+
{
116+
return View();
117+
}
118+
119+
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
120+
public IActionResult Error()
121+
{
122+
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
123+
}
124+
125+
[HttpGet]
126+
public async Task<IActionResult> UpdateTimeStamp()
127+
{
128+
await _redisDB.StringSetAsync(key, DateTime.UtcNow.ToString("s"));
129+
return Ok("Last timestamp: " + (await _redisDB.StringGetAsync(key)).ToString());
130+
131+
}
132+
}
86133
}
134+
87135
```
88136

89-
1. Open the Program.cs file and the following code snippet to instantiate a connection to your Azure Cache for Redis Instance.
137+
1. Open the Program.cs file and replace with the following code snippet which will instantiate a connection to your Azure Cache for Redis Instance using system assigned managed identity
90138
Note that
91139
- redisHostName is the hostname for the Azure Cache for Redis instance that you created earlier
92-
- webAppObjectId is the object (Principal) Id for your Azure App Service system assigned managed identity.
140+
- msiPrincipalID is the Principal Id for your Azure App Service system assigned managed identity.
93141

94142
```CSharp
95-
const string redisHostName = "cachename.redis.cache.windows.net";
96-
const string webAppObjectId = "someguid";
143+
using StackExchange.Redis;
144+
145+
var builder = WebApplication.CreateBuilder(args);
146+
97147

98-
var configOptions = await ConfigurationOptions.Parse($"{redisHostName}:6380").ConfigureForAzureWithSystemAssignedManagedIdentityAsync(webAppObjectId);
148+
// Add services to the container.
149+
builder.Services.AddControllersWithViews();
150+
151+
const string redisHostName = "yourcachename.redis.cache.windows.net";
152+
const string msiPrincipalID = "someguid";
153+
154+
var configOptions = await ConfigurationOptions.Parse($"{redisHostName}:6380").ConfigureForAzureWithSystemAssignedManagedIdentityAsync(msiPrincipalID);
99155

100156
var redisConnection = await ConnectionMultiplexer.ConnectAsync(configOptions);
101157
var redisDB = redisConnection.GetDatabase();
102158

103159
builder.Services.AddSingleton(redisDB);
104160

105161
var app = builder.Build();
106-
```
107162

163+
// Configure the HTTP request pipeline.
164+
if (!app.Environment.IsDevelopment())
165+
{
166+
app.UseExceptionHandler("/Home/Error");
167+
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
168+
app.UseHsts();
169+
}
170+
171+
app.UseHttpsRedirection();
172+
app.UseStaticFiles();
173+
174+
app.UseRouting();
108175

109-
## Clean up your deployment
176+
app.UseAuthorization();
110177

111-
To clean up your cluster, run the following commands:
178+
app.MapControllerRoute(
179+
name: "default",
180+
pattern: "{controller=Home}/{action=Index}/{id?}");
181+
182+
app.Run();
112183

113-
```bash
114-
kubectl delete deployment azure-vote-front
115-
kubectl delete service azure-vote-front
116184
```
117185

186+
### Publish updated web app to Azure App Service
187+
188+
1. Right click on your project and choose Publish. Follow instructions to publish the updated web app to the Azure App Service that you created earlier.
189+
190+
1. After publishing your web app successfully to Azure App Service, a browser window will open which loads your custom controller along with "Update timestamp" button.
191+
Click the button and see the latest timestamp when data in your Redis instance is updated.
192+
193+
## Clean up resources
194+
195+
In the preceding steps, you created Azure resources in a resource group. If you don't expect to need these resources in the future, you can delete them by deleting the resource group.
196+
197+
From your web app's Overview page in the Azure portal, select the myResourceGroup link under Resource group.
198+
On the resource group page, make sure that the listed resources are the ones you want to delete.
199+
Select Delete, type myResourceGroup in the text box, and then select Delete.
200+
118201
[!INCLUDE [cache-delete-resource-group](includes/cache-delete-resource-group.md)]
119202

120203
## Related content
121204

122-
- [Quickstart: Deploy an Azure Kubernetes Service (AKS) cluster using the Azure portal](/azure/aks/learn/quick-kubernetes-deploy-portal)
123-
- [AKS sample voting application](https://github.com/Azure-Samples/azure-voting-app-redis/tree/master)
205+
- [Learn More: Use Entra ID for authentication](/azure/azure-cache-for-redis/cache-azure-active-directory-for-authentication)
206+
- [Learn More: Role based access control](/azure/azure-cache-for-redis/cache-configure-role-based-access-control)

0 commit comments

Comments
 (0)