Skip to content

Commit 92dfd65

Browse files
Merge pull request #175878 from zhenlan/fullfx
Add a tutorial of how to use AppConfig in .NET Framework web apps
2 parents 314f1c5 + e3b2538 commit 92dfd65

8 files changed

+299
-62
lines changed

articles/azure-app-configuration/TOC.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@
4848
items:
4949
- name: ASP.NET Core
5050
href: enable-dynamic-configuration-aspnet-core.md
51+
- name: ASP.NET (.NET Framework)
52+
href: enable-dynamic-configuration-aspnet-netfx.md
5153
- name: .NET Core
5254
href: enable-dynamic-configuration-dotnet-core.md
5355
- name: .NET Framework
Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
---
2+
title: Tutorial for using Azure App Configuration dynamic configuration in an ASP.NET web application (.NET Framework) | Microsoft Docs
3+
description: In this tutorial, you learn how to dynamically update the configuration data for ASP.NET web applications (.NET Framework)
4+
services: azure-app-configuration
5+
author: zhenlan
6+
ms.service: azure-app-configuration
7+
ms.devlang: csharp
8+
ms.custom: devx-track-csharp
9+
ms.topic: tutorial
10+
ms.date: 10/12/2021
11+
ms.author: zhenlwa
12+
13+
#Customer intent: I want to dynamically update my ASP.NET web application (.NET Framework) to use the latest configuration data in App Configuration.
14+
---
15+
# Tutorial: Use dynamic configuration in an ASP.NET web application (.NET Framework)
16+
17+
Data from App Configuration can be loaded as App Settings in a .NET Framework application. For more information, see the [quickstart](./quickstart-dotnet-app.md). However, as is designed by the .NET Framework, the App Settings can only refresh upon application restart. The App Configuration .NET provider is a .NET Standard library. It supports caching and refreshing configuration dynamically without application restart. This tutorial shows how you can implement dynamic configuration updates in an ASP.NET Web Forms application. The same technique applies to .NET Framework MVC applications.
18+
19+
In this tutorial, you learn how to:
20+
21+
> [!div class="checklist"]
22+
> * Set up your ASP.NET web application to update its configuration in response to changes in an App Configuration store.
23+
> * Inject the latest configuration in requests to your application.
24+
25+
## Prerequisites
26+
27+
- Azure subscription - [create one for free](https://azure.microsoft.com/free/)
28+
- [Visual Studio](https://visualstudio.microsoft.com/vs)
29+
- [.NET Framework 4.7.2 or later](https://dotnet.microsoft.com/download/dotnet-framework)
30+
31+
## Create an App Configuration store
32+
33+
[!INCLUDE[Azure App Configuration resource creation steps](../../includes/azure-app-configuration-create.md)]
34+
35+
7. Select **Operations** > **Configuration explorer** > **Create** > **Key-value** to add the following key-values:
36+
37+
| Key | Value |
38+
|------------------------------------|-------------------------------------|
39+
| *TestApp:Settings:BackgroundColor* | *White* |
40+
| *TestApp:Settings:FontColor* | *Black* |
41+
| *TestApp:Settings:FontSize* | *40* |
42+
| *TestApp:Settings:Message* | *Data from Azure App Configuration* |
43+
| *TestApp:Settings:Sentinel* | *v1* |
44+
45+
Leave **Label** and **Content type** empty.
46+
47+
## Create an ASP.NET Web Application
48+
49+
1. Start Visual Studio and select **Create a new project**.
50+
51+
1. Select **ASP.NET Web Application (.NET Framework)** with C# from the project template list and press **Next**.
52+
53+
1. In **Configure your new project**, enter a project name. Under **Framework**, select **.NET Framework 4.7.2** or higher. Press **Create**.
54+
55+
1. In **Create a new ASP.NET Web Application**, select **Web Forms**. Press **Create**.
56+
57+
## Reload data from App Configuration
58+
59+
1. Right-click your project and select **Manage NuGet Packages**. On the **Browse** tab, search and add the latest version of the following NuGet package to your project.
60+
61+
*Microsoft.Extensions.Configuration.AzureAppConfiguration*
62+
63+
1. Open *Global.asax.cs* file and add following namespaces.
64+
```csharp
65+
using Microsoft.Extensions.Configuration;
66+
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
67+
```
68+
69+
1. Add the following static member variables to the `Global` class.
70+
```csharp
71+
public static IConfiguration Configuration;
72+
private static IConfigurationRefresher _configurationRefresher;
73+
```
74+
75+
1. Add an `Application_Start` method to the `Global` class. If the method already exists, add the following code to it.
76+
```csharp
77+
protected void Application_Start(object sender, EventArgs e)
78+
{
79+
ConfigurationBuilder builder = new ConfigurationBuilder();
80+
builder.AddAzureAppConfiguration(options =>
81+
{
82+
options.Connect(Environment.GetEnvironmentVariable("ConnectionString"))
83+
// Load all keys that start with `TestApp:`.
84+
.Select("TestApp:*")
85+
// Configure to reload configuration if the registered key 'TestApp:Settings:Sentinel' is modified.
86+
.ConfigureRefresh(refresh =>
87+
{
88+
refresh.Register("TestApp:Settings:Sentinel", refreshAll:true);
89+
.SetCacheExpiration(new TimeSpan(0, 5, 0));
90+
});
91+
_configurationRefresher = options.GetRefresher();
92+
});
93+
94+
Configuration = builder.Build();
95+
}
96+
```
97+
The `Application_Start` method is called upon the first request to your web application. It is called only once during the application's life cycle. As such it is a good place to initialize your `IConfiguration` object and load data from App Configuration.
98+
99+
In the `ConfigureRefresh` method, a key within your App Configuration store is registered for change monitoring. The `refreshAll` parameter to the `Register` method indicates that all configuration values should be refreshed if the registered key changes. In this example, the key *TestApp:Settings:Sentinel* is a *sentinel* key that you update after you complete the change of all other keys. When a change is detected, your application refreshes all configuration values. This approach helps to ensure the consistency of configuration in your application compared to monitoring all keys for changes.
100+
101+
The `SetCacheExpiration` method specifies the minimum time that must elapse before a new request is made to App Configuration to check for any configuration changes. In this example, you override the default expiration time of 30 seconds, specifying a time of 5 minutes instead. It reduces the potential number of requests made to your App Configuration store.
102+
103+
104+
1. Add an `Application_BeginRequest` method to the `Global` class. If the method already exists, add the following code to it.
105+
```csharp
106+
protected void Application_BeginRequest(object sender, EventArgs e)
107+
{
108+
_ = _configurationRefresher.TryRefreshAsync();
109+
}
110+
```
111+
Calling the `ConfigureRefresh` method alone won't cause the configuration to refresh automatically. You call the `TryRefreshAsync` method at the beginning of every request to signal a refresh. This design ensures your application only sends requests to App Configuration when it is actively receiving requests.
112+
113+
Calling `TryRefreshAsync` is a no-op before the configured cache expiration time elapses, so its performance impact is minimal. When a request is made to App Configuration, as you don't wait on the task, the configuration is refreshed asynchronously without blocking the execution of the current request. The current request may not get the updated configuration values, but subsequent requests will do.
114+
115+
If the call `TryRefreshAsync` fails for any reason, your application will continue to use the cached configuration. Another attempt will be made when the configured cache expiration time has passed again, and the `TryRefreshAsync` call is triggered by a new request to your application.
116+
117+
## Use the latest configuration data
118+
119+
1. Open *Default.aspx* and replace its content with the following markup. Make sure the *Inherits* attribute matches the namespace and the class name of your application.
120+
```xml
121+
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebFormApp.Default" %>
122+
123+
<!DOCTYPE html>
124+
125+
<html xmlns="http://www.w3.org/1999/xhtml">
126+
<head runat="server">
127+
<title>Azure App Configuration Web Forms Demo</title>
128+
</head>
129+
<body id="body" runat="server">
130+
<form id="form1" runat="server">
131+
<div style="text-align: center">
132+
<asp:Label ID="message" runat="server" />
133+
</div>
134+
</form>
135+
</body>
136+
</html>
137+
```
138+
139+
1. Open *Default.aspx.cs* and update it with the following code.
140+
```cs
141+
using System;
142+
using System.Web.UI.WebControls;
143+
144+
namespace WebFormApp
145+
{
146+
public partial class Default : System.Web.UI.Page
147+
{
148+
protected void Page_Load(object sender, EventArgs e)
149+
{
150+
// Read configuration from the IConfiguration object loaded from Azure App Configuration
151+
string messageText = Global.Configuration["TestApp:Settings:Message"] ?? "Please add the key \"TestApp:Settings:Message\" in your Azure App Configuration store.";
152+
string messageFontSize = Global.Configuration["TestApp:Settings:FontSize"] ?? "20";
153+
string messageFontColor = Global.Configuration["TestApp:Settings:FontColor"] ?? "Black";
154+
string backgroundColor = Global.Configuration["TestApp:Settings:BackgroundColor"] ?? "White";
155+
156+
message.Text = messageText;
157+
message.Font.Size = FontUnit.Point(int.Parse(messageFontSize));
158+
message.ForeColor = System.Drawing.Color.FromName(messageFontColor);
159+
body.Attributes["bgcolor"] = backgroundColor;
160+
}
161+
}
162+
}
163+
```
164+
165+
## Build and run the application
166+
167+
1. Set an environment variable named **ConnectionString** to the read-only key connection string obtained during your App Configuration store creation.
168+
169+
If you use the Windows command prompt, run the following command:
170+
```console
171+
setx ConnectionString "connection-string-of-your-app-configuration-store"
172+
```
173+
174+
If you use Windows PowerShell, run the following command:
175+
```powershell
176+
$Env:ConnectionString = "connection-string-of-your-app-configuration-store"
177+
```
178+
179+
1. Restart Visual Studio to allow the change to take effect.
180+
181+
1. Press Ctrl + F5 to build and run the web application.
182+
183+
![App launch local](./media/dotnet-fx-web-app-launch.png)
184+
185+
1. In the Azure portal, navigate to the **Configuration explorer** of your App Configuration store, and update the value of the following keys. Remember to update the sentinel key *TestApp:Settings:Sentinel* at last.
186+
187+
| Key | Value |
188+
|------------------------------------|--------------------------------------------------------------|
189+
| *TestApp:Settings:BackgroundColor* | *Green* |
190+
| *TestApp:Settings:FontColor* | *LightGray* |
191+
| *TestApp:Settings:Message* | *Data from Azure App Configuration - now with live updates!* |
192+
| *TestApp:Settings:Sentinel* | *v2* |
193+
194+
1. Refresh the browser page to see the new configuration settings. You may need to refresh more than once for the changes to be reflected or change your cache expiration time to less than 5 minutes.
195+
196+
![App refresh local](./media/dotnet-fx-web-app-refresh.png)
197+
198+
> [!NOTE]
199+
> You can download the example code used in this tutorial from the [Azure App Configuration GitHub repo](https://github.com/Azure/AppConfiguration/tree/main/examples/DotNetFramework/WebFormApp).
200+
201+
## Clean up resources
202+
203+
[!INCLUDE [azure-app-configuration-cleanup](../../includes/azure-app-configuration-cleanup.md)]
204+
205+
## Next steps
206+
207+
In this tutorial, you enabled your ASP.NET Web Forms application to dynamically refresh configuration settings from App Configuration. To learn how to enable dynamic configuration in a .NET Framework app, continue to the next tutorial:
208+
209+
> [!div class="nextstepaction"]
210+
> [Enable dynamic configuration in .NET Framework apps](./enable-dynamic-configuration-dotnet.md)
211+
212+
To learn how to use an Azure managed identity to streamline the access to App Configuration, continue to the next tutorial:
213+
214+
> [!div class="nextstepaction"]
215+
> [Managed identity integration](./howto-integrate-azure-managed-service-identity.md)

0 commit comments

Comments
 (0)