教程:在 ASP.NET Core 应用中使用动态配置Tutorial: Use dynamic configuration in an ASP.NET Core app

ASP.NET Core 有可插拔的配置系统,可以从各种源读取配置数据。ASP.NET Core has a pluggable configuration system that can read configuration data from a variety of sources. 它可以动态处理更改,而不会导致应用程序重启。It can handle changes dynamically without causing an application to restart. ASP.NET Core 支持将配置设置绑定到强类型 .NET 类。ASP.NET Core supports the binding of configuration settings to strongly typed .NET classes. 它通过使用各种 IOptions<T> 模式将其注入到代码中。It injects them into your code by using the various IOptions<T> patterns. 其中一种模式(特别是 IOptionsSnapshot<T>)会在基础数据发生更改时自动重载应用程序的配置。One of these patterns, specifically IOptionsSnapshot<T>, automatically reloads the application's configuration when the underlying data changes. 可将 IOptionsSnapshot<T> 注入应用程序的控制器,以访问 Azure 应用配置中存储的最新配置。You can inject IOptionsSnapshot<T> into controllers in your application to access the most recent configuration stored in Azure App Configuration.

此外,还可以设置应用配置 ASP.NET Core 客户端库,以使用中间件动态刷新一组配置设置。You also can set up the App Configuration ASP.NET Core client library to refresh a set of configuration settings dynamically using a middleware. 每次只要 Web 应用收到请求,配置设置就会使用配置存储进行更新。The configuration settings get updated with the configuration store each time as long as the web app receives requests.

Azure 应用程序配置会自动缓存每项设置,避免过多调用配置存储。App Configuration automatically caches each setting to avoid too many calls to the configuration store. 刷新操作会等待,直到某项设置的已缓存值过期才更新该设置,即使其值在配置存储中发生了更改。The refresh operation waits until the cached value of a setting expires to update that setting, even when its value changes in the configuration store. 默认缓存过期时间为 30 秒。The default cache expiration time is 30 seconds. 可以根据需要覆盖此过期时间。You can override this expiration time, if necessary.

本教程演示如何在代码中实现动态配置更新。This tutorial shows how you can implement dynamic configuration updates in your code. 它建立在快速入门中介绍的 Web 应用之上。It builds on the web app introduced in the quickstarts. 在继续操作之前,请先完成使用应用程序配置创建 ASP.NET Core 应用Before you continue, finish Create an ASP.NET Core app with App Configuration first.

你可以使用任何代码编辑器执行本教程中的步骤。You can use any code editor to do the steps in this tutorial. Visual Studio Code 是 Windows、macOS 和 Linux 平台上提供的一个卓越选项。Visual Studio Code is an excellent option that's available on the Windows, macOS, and Linux platforms.

在本教程中,你将了解如何执行以下操作:In this tutorial, you learn how to:

  • 设置应用程序,使其能够更新配置以响应应用程序配置存储区中的更改。Set up your application to update its configuration in response to changes in an App Configuration store.
  • 在应用程序的控制器中注入最新配置。Inject the latest configuration in your application's controllers.

先决条件Prerequisites

若要完成本教程,请安装 .NET Core SDKTo do this tutorial, install the .NET Core SDK.

如果没有 Azure 试用版订阅,请在开始前创建一个试用版订阅If you don't have an Azure trail subscription, create a trial subscription before you begin.

在继续操作之前,请先完成使用应用程序配置创建 ASP.NET Core 应用Before you continue, finish Create an ASP.NET Core app with App Configuration first.

添加 sentinel 键Add a sentinel key

sentinel 键 是用于在配置更改时发出信号的特殊键。A sentinel key is a special key used to signal when configuration has changed. 应用会监视 sentinel 键以了解更改情况。Your app monitors the sentinel key for changes. 检测到更改时,刷新所有配置值。When a change is detected, you refresh all configuration values. 与监视所有键以了解更改情况相比,这种方法可减少应用对 Azure 应用程序配置发出的请求的总数。This approach reduces the overall number of requests made by your app to App Configuration, compared to monitoring all keys for changes.

  1. 在 Azure 门户中,选择“配置资源管理器”>“创建”>“键-值” 。In the Azure portal, select Configuration Explorer > Create > Key-value.

  2. 输入 TestApp:Settings:Sentinel 作为“键”。 For Key, enter TestApp:Settings:Sentinel. 输入 1 作为“值”。For Value, enter 1. 将“标签”和“内容类型”留空 。Leave Label and Content type blank.

  3. 选择“应用”。 Select Apply.

备注

如果不使用 Sentinel 密钥,则需手动注册要监视的每个密钥。If you aren't using a sentinel key, you need to manually register every key you want to watch.

从应用配置重载数据Reload data from App Configuration

  1. 通过运行以下命令,添加对 Microsoft.Azure.AppConfiguration.AspNetCore NuGet 包的引用:Add a reference to the Microsoft.Azure.AppConfiguration.AspNetCore NuGet package by running the following command:

    dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore
    
  2. 打开 Program.cs,并更新 CreateWebHostBuilder 方法以添加 config.AddAzureAppConfiguration() 方法。Open Program.cs, and update the CreateWebHostBuilder method to add the config.AddAzureAppConfiguration() method.

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var settings = config.Build();
    
                config.AddAzureAppConfiguration(options =>
                {
                    options.Connect(settings["ConnectionStrings:AppConfig"])
                           .ConfigureRefresh(refresh =>
                                {
                                    refresh.Register("TestApp:Settings:Sentinel", refreshAll: true)
                                           .SetCacheExpiration(new TimeSpan(0, 5, 0));
                                });
                });
            })
            .UseStartup<Startup>();
    

    ConfigureRefresh 方法用于指定在刷新操作触发时通过应用程序配置存储区更新配置数据所用的设置。The ConfigureRefresh method is used to specify the settings used to update the configuration data with the App Configuration store when a refresh operation is triggered. Register 方法的 refreshAll 参数指示在 sentinel 键更改时应刷新所有配置值。The refreshAll parameter to the Register method indicates that all configuration values should be refreshed if the sentinel key changes.

    此外,SetCacheExpiration 方法会重写默认的缓存过期时间(30 秒),改为指定一个 5 分钟的时间。Also, the SetCacheExpiration method overrides the default cache expiration time of 30 seconds, specifying a time of 5 minutes instead. 这会减少对 Azure 应用程序配置发出的请求数。This reduces the number of requests made to App Configuration.

    备注

    出于测试目的,可能需要缩短缓存的过期时间。For testing purposes, you may want to lower the cache expiration time.

    为了实际触发刷新操作,需要配置刷新中间件,使应用程序在发生任何更改时刷新配置数据。To actually trigger a refresh operation, you'll need to configure a refresh middleware for the application to refresh the configuration data when any change occurs. 稍后会介绍如何执行此操作。You'll see how to do this in a later step.

  3. 添加 Settings.cs 文件,用于定义和实现新的 Settings 类 。Add a Settings.cs file that defines and implements a new Settings class.

    namespace TestAppConfig
    {
        public class Settings
        {
            public string BackgroundColor { get; set; }
            public long FontSize { get; set; }
            public string FontColor { get; set; }
            public string Message { get; set; }
        }
    }
    
  4. 打开 Startup.cs ,然后在 ConfigureServices 方法中使用 IServiceCollection.Configure<T> 将配置数据绑定到 Settings 类。Open Startup.cs, and use IServiceCollection.Configure<T> in the ConfigureServices method to bind configuration data to the Settings class.

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<Settings>(Configuration.GetSection("TestApp:Settings"));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }
    

    提示

    若要了解有关读取配置值时的选项模式的详细信息,请参阅 ASP.NET Core 中的选项模式To learn more about the options pattern when reading configuration values, see Options Patterns in ASP.NET Core.

  5. 更新 Configure 方法以添加 UseAzureAppConfiguration 中间件,从而允许在 ASP.NET Core Web 应用继续接收请求的同时,更新已为刷新操作注册的配置设置。Update the Configure method, adding the UseAzureAppConfiguration middleware to allow the configuration settings registered for refresh to be updated while the ASP.NET Core web app continues to receive requests.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseAzureAppConfiguration();
    
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
    
        app.UseMvc();
    }
    

    该中间件使用 Program.csAddAzureAppConfiguration 方法中指定的刷新配置,以针对 ASP.NET Core Web 应用收到的每个请求触发刷新。The middleware uses the refresh configuration specified in the AddAzureAppConfiguration method in Program.cs to trigger a refresh for each request received by the ASP.NET Core web app. 对于每个请求,均会触发刷新操作,并且客户端库会检查已注册的配置设置的缓存值是否过期。For each request, a refresh operation is triggered and the client library checks if the cached value for the registered configuration setting has expired. 如果它已过期,则会刷新它。If it's expired, it's refreshed.

使用最新的配置数据Use the latest configuration data

  1. 打开 Controllers 目录中的 HomeController.cs,并添加对 Microsoft.Extensions.Options 包的引用。Open HomeController.cs in the Controllers directory, and add a reference to the Microsoft.Extensions.Options package.

    using Microsoft.Extensions.Options;
    
  2. 更新 HomeController 类,通过依赖项注入接收 Settings 并利用其值。Update the HomeController class to receive Settings through dependency injection, and make use of its values.

    public class HomeController : Controller
    {
        private readonly Settings _settings;
        public HomeController(IOptionsSnapshot<Settings> settings)
        {
            _settings = settings.Value;
        }
    
        public IActionResult Index()
        {
            ViewData["BackgroundColor"] = _settings.BackgroundColor;
            ViewData["FontSize"] = _settings.FontSize;
            ViewData["FontColor"] = _settings.FontColor;
            ViewData["Message"] = _settings.Message;
    
            return View();
        }
    }
    
  3. 在“视图”>“主页”目录中打开 Index.cshtml,并将其内容替换为以下脚本:Open Index.cshtml in the Views > Home directory, and replace its content with the following script:

    <!DOCTYPE html>
    <html lang="en">
    <style>
        body {
            background-color: @ViewData["BackgroundColor"]
        }
        h1 {
            color: @ViewData["FontColor"];
            font-size: @ViewData["FontSize"]px;
        }
    </style>
    <head>
        <title>Index View</title>
    </head>
    <body>
        <h1>@ViewData["Message"]</h1>
    </body>
    </html>
    

在本地生成并运行应用Build and run the app locally

  1. 要通过使用 .NET Core CLI 生成应用,请在命令行界面中执行以下命令:To build the app by using the .NET Core CLI, run the following command in the command shell:
        dotnet build
  1. 生成成功完成后,请运行以下命令以在本地运行 Web 应用:After the build successfully completes, run the following command to run the web app locally:
        dotnet run
  1. 打开浏览器窗口,访问 dotnet run 输出中显示的 URL。Open a browser window, and go to the URL shown in the dotnet run output.

    在本地启动快速入门应用

  2. 登录 Azure 门户Sign in to the Azure portal. 选择“所有资源”,然后选择在快速入门中创建的应用程序配置存储区实例 。Select All resources, and select the App Configuration store instance that you created in the quickstart.

  3. 选择“配置资源管理器” 并更新以下键的值:Select Configuration Explorer, and update the values of the following keys:

    密钥Key Value
    TestApp:Settings:BackgroundColorTestApp:Settings:BackgroundColor greengreen
    TestApp:Settings:FontColorTestApp:Settings:FontColor lightGraylightGray
    TestApp:Settings:MessageTestApp:Settings:Message Azure 应用配置中的数据 - 现可实时更新!Data from Azure App Configuration - now with live updates!
    TestApp:Settings:SentinelTestApp:Settings:Sentinel 22
  4. 刷新浏览器页面,查看新的配置设置。Refresh the browser page to see the new configuration settings. 可能需要多次刷新才能反映所做的更改。You may need to refresh more than once for the changes to be reflected.

    在本地启动更新的快速入门应用

清理资源Clean up resources

如果不想继续使用本文中创建的资源,请删除此处创建的资源组以避免产生费用。If you do not want to continue using the resources created in this article, delete the resource group you created here to avoid charges.

重要

删除资源组的操作不可逆。Deleting a resource group is irreversible. 将永久删除资源组以及其中的所有资源。The resource group and all the resources in it are permanently deleted. 请确保不要意外删除错误的资源组或资源。Make sure that you don't accidentally delete the wrong resource group or resources. 如果在包含要保留的其他资源的资源组中创建了本文的资源,请从相应的窗格中单独删除每个资源,而不是删除该资源组。If you created the resources for this article inside a resource group that contains other resources you want to keep, delete each resource individually from its respective pane instead of deleting the resource group.

  1. 登录到 Azure 门户,然后选择“资源组”。Sign in to the Azure portal, and select Resource groups.
  2. 在“按名称筛选”框中,输入资源组的名称。In the Filter by name box, enter the name of your resource group.
  3. 在结果列表中,选择资源组名称以查看概述。In the result list, select the resource group name to see an overview.
  4. 选择“删除资源组”。Select Delete resource group.
  5. 系统会要求确认是否删除资源组。You're asked to confirm the deletion of the resource group. 重新键入资源组的名称进行确认,然后选择“删除” 。Enter the name of your resource group to confirm, and select Delete.

片刻之后,将会删除该资源组及其所有资源。After a few moments, the resource group and all its resources are deleted.

后续步骤Next steps

在本教程中,你使得 ASP.NET Core Web 应用能够从应用程序配置中动态刷新配置设置。In this tutorial, you enabled your ASP.NET Core web app to dynamically refresh configuration settings from App Configuration. 若要了解如何使用 Azure 托管标识来简化对应用程序配置的访问,请继续学习下一篇教程。To learn how to use an Azure-managed identity to streamline the access to App Configuration, continue to the next tutorial.