快速入门:使用 Azure 应用配置创建 ASP.NET Core 应用Quickstart: Create an ASP.NET Core app with Azure App Configuration

本快速入门将使用 Azure 应用程序配置来集中存储和管理 ASP.NET Core 应用的应用程序设置。In this quickstart, you'll use Azure App Configuration to centralize storage and management of application settings for an ASP.NET Core app. ASP.NET Core 使用由应用指定的一个或多个数据源的设置,生成基于键值的单个配置对象。ASP.NET Core builds a single, key-value-based configuration object using settings from one or more data sources specified by an app. 这些数据源称为配置提供程序 。These data sources are known as configuration providers. 由于应用程序配置的 .NET Core 客户端作为配置提供程序实现,因此服务就像是另一个数据源。Because App Configuration's .NET Core client is implemented as a configuration provider, the service appears like another data source.

先决条件Prerequisites

创建应用配置存储区Create an App Configuration store

  1. 若要创建新应用程序配置存储区,请登录 Azure 门户To create a new App Configuration store, sign in to the Azure portal. 在主页的左上角,选择“创建资源” 。In the upper-left corner of the home page, select Create a resource. 在“搜索市场”框中,输入“应用程序配置”并选择 Enter 。In the Search the Marketplace box, enter App Configuration and select Enter.

    搜索应用配置

  2. 在搜索结果中选择“应用程序配置”,然后选择“创建” 。Select App Configuration from the search results, and then select Create.

    选择“创建”

  3. 在“创建应用配置”窗格中,输入以下设置:On the Create App Configuration pane, enter the following settings:

    设置Setting 建议的值Suggested value 说明Description
    订阅Subscription 订阅Your subscription 选择要用来测试应用配置的 Azure 订阅。Select the Azure subscription that you want to use to test App Configuration. 如果帐户只有一个订阅,则会自动选择该订阅并且不显示“订阅”列表 。If your account has only one subscription, it's automatically selected and the Subscription list isn't displayed.
    资源组Resource group AppConfigTestResources AppConfigTestResources 为应用程序配置存储区资源选择或创建资源组。Select or create a resource group for your App Configuration store resource. 此组可用于组织多个资源,删除该资源组可以同时删除这些资源。This group is useful for organizing multiple resources that you might want to delete at the same time by deleting the resource group. 有关详细信息,请参阅使用资源组管理 Azure 资源For more information, see Use resource groups to manage your Azure resources.
    资源名称Resource name 全局唯一名称Globally unique name 输入要用于应用程序配置存储区资源的唯一资源名称。Enter a unique resource name to use for the App Configuration store resource. 该名称必须是包含 5 到 50 个字符的字符串,只能包含数字、字母和 - 字符。The name must be a string between 5 and 50 characters and contain only numbers, letters, and the - character. 该名称的开头或末尾不能是 - 字符。The name can't start or end with the - character.
    位置Location 中国东部 2China East 2 使用“位置”指定在其中托管应用配置存储区的地理位置 。Use Location to specify the geographic location in which your app configuration store is hosted. 为获得最佳性能,请在应用程序的其他组件所在的同一区域创建资源。For the best performance, create the resource in the same region as other components of your application.
    定价层Pricing tier 免费Free 选择所需的定价层。Select the desired pricing tier. 有关详细信息,请参阅应用配置定价页For more information, see the App Configuration pricing page.
  4. 选择“查看 + 创建”以验证自己的设置 。Select Review + create to validate your settings.

  5. 选择“创建”。Select Create. 部署可能需要几分钟。The deployment might take a few minutes.

  6. 部署完成后,导航到“应用程序配置”资源。After the deployment finishes, navigate to the App Configuration resource. 选择“设置” > “访问密钥”。Select Settings > Access keys. 记下只读主密钥连接字符串。Make a note of the primary read-only key connection string. 稍后将使用此连接字符串来配置应用程序,以与创建的应用程序配置存储区进行通信。You'll use this connection string later to configure your application to communicate with the App Configuration store that you created.

  1. 选择“操作” > “配置资源管理器” > “创建” > “键-值”来添加以下键值对 :Select Operations > Configuration explorer > Create > Key-value to add the following key-value pairs:

    密钥Key Value
    TestApp:Settings:BackgroundColor #FFF#FFF
    TestApp:Settings:FontColor #000#000
    TestApp:Settings:FontSize 2424
    TestApp:Settings:Message Azure 应用配置的数据Data from Azure App Configuration

    暂时将“标签”和“内容类型”保留为空 。Leave Label and Content type empty for now. 选择“应用”。Select Apply.

创建一个 ASP.NET Core Web 应用Create an ASP.NET Core web app

使用 .NET Core 命令行接口 (CLI) 创建新的 ASP.NET Core MVC 项目。Use the .NET Core command-line interface (CLI) to create a new ASP.NET Core MVC project.

在新的 TestAppConfig 文件夹中,运行以下命令,创建 ASP.NET Core MVC 项目:Run the following command to create an ASP.NET Core MVC project in a new TestAppConfig folder:

dotnet new mvc --no-https --output TestAppConfig

添加机密管理器Add Secret Manager

一个称为“机密管理器”的工具会存储敏感数据,以用于项目树之外的开发工作。A tool called Secret Manager stores sensitive data for development work outside of your project tree. 此方法有助于防止意外共享源代码中的应用密码。This approach helps prevent the accidental sharing of app secrets within source code. 完成以下步骤可在 ASP.NET Core 项目中启用机密管理器:Complete the following steps to enable the use of Secret Manager in the ASP.NET Core project:

导航到项目的根目录,并运行以下命令以在项目中启用机密存储:Navigate to the project's root directory, and run the following command to enable secrets storage in the project:

dotnet user-secrets init

包含 GUID 的 UserSecretsId 元素将添加到 .csproj 文件中:A UserSecretsId element containing a GUID is added to the .csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web">
    
    <PropertyGroup>
        <TargetFramework>netcoreapp3.1</TargetFramework>
        <UserSecretsId>79a3edd0-2092-40a2-a04d-dcb46d5ca9ed</UserSecretsId>
    </PropertyGroup>

</Project>

提示

若要详细了解机密管理器,请参阅在开发 ASP.NET Core 应用时安全存储应用机密To learn more about Secret Manager, see Safe storage of app secrets in development in ASP.NET Core.

连接到应用程序配置存储区Connect to the App Configuration store

  1. 运行以下命令,添加 Microsoft.Azure.AppConfiguration.AspNetCore NuGet 包引用:Run the following command to add a Microsoft.Azure.AppConfiguration.AspNetCore NuGet package reference:

    dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore
    
  2. 在 .csproj 文件所在的同一目录中运行以下命令。Run the following command in the same directory as the .csproj file. 该命令使用机密管理器存储名为 ConnectionStrings:AppConfig 的机密,该机密存储应用程序配置存储区的连接字符串。The command uses Secret Manager to store a secret named ConnectionStrings:AppConfig, which stores the connection string for your App Configuration store. <your_connection_string> 占位符替换为应用程序配置存储区的连接字符串。Replace the <your_connection_string> placeholder with your App Configuration store's connection string. 可以在 Azure 门户的“访问密钥” 下找到该连接字符串。You can find the connection string under Access Keys in the Azure portal.

    dotnet user-secrets set ConnectionStrings:AppConfig "<your_connection_string>"
    

    重要

    有些 shell 会截断连接字符串,除非将连接字符串括在引号中。Some shells will truncate the connection string unless it's enclosed in quotes. 确保 dotnet user-secrets 命令的输出显示整个连接字符串。Ensure that the output of the dotnet user-secrets command shows the entire connection string. 如果未显示,请重新运行该命令,并将连接字符串括在引号中。If it doesn't, rerun the command, enclosing the connection string in quotes.

    机密管理器仅用于本地测试 web 应用程序。Secret Manager is used only to test the web app locally. 将应用部署到 Azure 应用服务后,可以使用应用服务中的“连接字符串”应用程序设置,而无需使用机密管理器来存储连接字符串。When the app is deployed to Azure App Service, use the Connection Strings application setting in App Service instead of Secret Manager to store the connection string.

    使用 .NET Core 配置 API 访问此机密。Access this secret using the .NET Core Configuration API. 在所有支持的平台上,冒号 (:) 可以在配置 API 的配置名称中使用。A colon (:) works in the configuration name with the Configuration API on all supported platforms. 有关详细信息,请参阅配置键和值For more information, see Configuration keys and values.

  3. 在 Program.cs 中,添加对 .NET Core 配置提供程序 API 命名空间的引用:In Program.cs, add a reference to the .NET Core Configuration API namespace:

    using Microsoft.Extensions.Configuration;
    
  4. 通过调用 AddAzureAppConfiguration 方法,更新 CreateWebHostBuilder 方法以使用应用配置。Update the CreateWebHostBuilder method to use App Configuration by calling the AddAzureAppConfiguration method.

    重要

    CreateHostBuilder 替换 .NET Core 3.x 中的 CreateWebHostBuilderCreateHostBuilder replaces CreateWebHostBuilder in .NET Core 3.x. 根据环境选择正确的语法。Select the correct syntax based on your environment.

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
                webBuilder.ConfigureAppConfiguration(config =>
                {
                    var settings = config.Build();
                    var connection = settings.GetConnectionString("AppConfig");
                    config.AddAzureAppConfiguration(connection);
                }).UseStartup<Startup>());
    

    进行上述更改后,应用程序配置的配置提供程序就已注册到 .NET Core 配置 API。With the preceding change, the configuration provider for App Configuration has been registered with the .NET Core Configuration API.

从应用程序配置存储区读取数据Read from the App Configuration store

完成下面的步骤,读取和显示存储在应用程序配置存储区中的值。Complete the following steps to read and display values stored in the App Configuration store. 可使用 .NET Core 配置 API 访问此存储区。The .NET Core Configuration API will be used to access the store. 使用 Razor 语法显示键值。Razor syntax will be used to display the keys' values.

打开 <app root>/Views/Home/Index.cshtml,并将其内容替换为以下代码:Open <app root>/Views/Home/Index.cshtml, and replace its content with the following code:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<style>
    body {
        background-color: @Configuration["TestApp:Settings:BackgroundColor"]
    }
    h1 {
        color: @Configuration["TestApp:Settings:FontColor"];
        font-size: @Configuration["TestApp:Settings:FontSize"]px;
    }
</style>

<h1>@Configuration["TestApp:Settings:Message"]</h1>

在上述代码中,按如下所示使用应用程序配置存储区的键:In the preceding code, the App Configuration store's keys are used as follows:

  • TestApp:Settings:BackgroundColor 键的值分配给 CSS background-color 属性。The TestApp:Settings:BackgroundColor key's value is assigned to the CSS background-color property.
  • TestApp:Settings:FontColor 键的值分配给 CSS color 属性。The TestApp:Settings:FontColor key's value is assigned to the CSS color property.
  • TestApp:Settings:FontSize 键的值分配给 CSS font-size 属性。The TestApp:Settings:FontSize key's value is assigned to the CSS font-size property.
  • TestApp:Settings:Message 键的值显示为标题。The TestApp:Settings:Message key's value is displayed as a heading.

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

  1. 若要使用 .NET Core CLI 生成应用,请导航到项目的根目录。To build the app using the .NET Core CLI, navigate to the root directory of your project. 在命令行界面中运行以下命令:Run the following command in the command shell:

    dotnet build
    
  2. 生成成功完成后,请运行以下命令以在本地运行 Web 应用:After the build completes successfully, run the following command to run the web app locally:

    dotnet run
    
  3. 如果要在本地计算机上操作,请使用浏览器导航到 http://localhost:5000If you're working on your local machine, use a browser to navigate to http://localhost:5000. 此地址是在本地托管的 Web 应用的默认 URL。This address is the default URL for the locally hosted web app.

    找到“Web 预览”按钮

    系统提示配置预览端口时,请输入“5000”,然后选择“打开并浏览”。When prompted to configure the port for preview, enter 5000 and select Open and browse. 网页将显示“数据来自 Azure 应用程序配置”。The web page will read "Data from Azure App Configuration."

清理资源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

在本快速入门中,请执行以下操作:In this quickstart, you:

  • 预配新的应用程序配置存储区。Provisioned a new App Configuration store.
  • 注册应用程序配置存储区的 .NET Core 配置提供程序。Registered the App Configuration store's .NET Core configuration provider.
  • 使用配置提供程序读取应用程序配置存储区的键。Read the App Configuration store's keys with the configuration provider.
  • 使用 Razor 语法显示应用程序配置存储区的键值。Displayed the App Configuration store's key values using Razor syntax.

若要了解如何配置 ASP.NET Core 应用以动态刷新配置设置,请继续学习下一个教程。To learn how to configure your ASP.NET Core app to dynamically refresh configuration settings, continue to the next tutorial.