快速入門:使用 Azure 應用程式設定建立 ASP.NET Core 應用程式Quickstart: Create an ASP.NET Core app with Azure App Configuration

在本快速入門中,您會將 Azure 應用程式組態納入 ASP.NET Core 應用程式中,以集中儲存和管理應用程式設定 (與您的程式碼分開)。In this quickstart, you incorporate Azure App Configuration into an ASP.NET Core app to centralize storage and management of application settings separate from your code. ASP.NET Core 會使用應用程式所指定一或多個資料來源中的設定,來建置一個以索引鍵-值為基礎的設定物件。ASP.NET Core builds a single key-value-based configuration object by using settings from one or more data sources that are specified by an application. 這些資料來源稱為「設定提供者」 。These data sources are known as configuration providers. 因為應用程式設定的 .NET Core 用戶端會實作為這類提供者,服務看來就像其他資料來源。Because App Configuration's .NET Core client is implemented as such a provider, the service appears like another data source.


建立應用程式設定存放區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 pane, select +Create a resource. 在 [搜尋 Marketplace] 方塊中輸入應用程式組態,然後選取 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 App Configuration > Create pane, enter the following settings:

    設定Setting 建議的值Suggested value 說明Description
    資源名稱Resource name 全域唯一的名稱Globally unique name 輸入要對應用程式組態存放區資源使用的唯一資源名稱。Enter a unique resource name to use for the App Configuration store resource. 名稱必須是介於 1 到 63 個字元的字串,而且只能包含數字、字母和 - 字元。The name must be a string between 1 and 63 characters and contain only numbers, letters, and the - character. 名稱的開頭或結尾不能是 - 字元,且連續的 - 字元無效。The name can't start or end with the - character, and consecutive - characters aren't valid.
    訂用帳戶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 AppConfigTestResourcesAppConfigTestResources 為應用程式組態存放區資源選取或建立資源群組。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.
    位置Location 美國中部Central US 使用 [位置] 來指定裝載應用程式設定存放區所在的地理位置。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.


  4. 選取 [建立] 。Select Create. 部署可能需要幾分鐘的時間才能完成。The deployment might take a few minutes to finish.

  5. 完成部署之後,請選取 [設定] > [存取金鑰] 。After the deployment is finished, select Settings > Access Keys. 記下主要唯讀或主要讀寫索引鍵連接字串。Make a note of either the primary read-only or primary read-write 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 Configuration Explorer > + Create to add the following key-value pairs:

    KeyKey Value
    TestApp:Settings:BackgroundColorTestApp:Settings:BackgroundColor 白色White
    TestApp:Settings:FontSizeTestApp:Settings:FontSize 2424
    TestApp:Settings:FontColorTestApp:Settings:FontColor 黑色Black
    TestApp:Settings:MessageTestApp:Settings:Message Azure 應用程式設定的值Data from Azure App Configuration

    目前先讓 [標籤] 和 [內容類型] 保持空白。Leave Label and Content Type empty for now.

建立 ASP.NET Core Web 應用程式Create an ASP.NET Core web app

您會使用 .NET Core 命令列介面 (CLI) 來建立新的 ASP.NET Core MVC Web 應用程式專案。You use the .NET Core command-line interface (CLI) to create a new ASP.NET Core MVC web app project. 使用 .NET Core CLI 而非 Visual Studio 的好處,在於 .NET Core CLI 可同時於 Windows、macOS 及 Linux 平台上取得。The advantage of using the .NET Core CLI over Visual Studio is that it's available across the Windows, macOS, and Linux platforms.

  1. 為您的專案建立新資料夾。Create a new folder for your project. 在本快速入門中,會將其命名為 TestAppConfigFor this quickstart, name it TestAppConfig.

  2. 在新的資料夾中,執行下列命令以建立新的 ASP.NET Core MVC Web 應用程式專案:In the new folder, run the following command to create a new ASP.NET Core MVC web app project:

     dotnet new mvc --no-https

新增祕密管理員Add Secret Manager

若要使用秘密管理員,請將 UserSecretsId 元素新增至 .csproj 檔案。To use Secret Manager, add a UserSecretsId element to your .csproj file.

  • 開啟 .csproj 檔案。Open the .csproj file. 新增 UserSecretsId 元素,如下所示。Add a UserSecretsId element as shown here. 您可以使用相同的 GUID,也可以將此值取代為您自己的值。You can use the same GUID, or you can replace this value with your own. 儲存檔案。Save the file.

    <Project Sdk="Microsoft.NET.Sdk.Web">
        <PackageReference Include="Microsoft.AspNetCore.App" />
        <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />

祕密管理員工具能儲存專案樹狀結構外開發工作的敏感性資料。The Secret Manager tool 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 中的開發中安全儲存應用程式秘密For more information on Secret Manager, please see Safe storage of app secrets in development in ASP.NET Core

連線至應用程式設定存放區Connect to an app configuration store

  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 --version 2.0.0-preview-010060003-1250
  2. 執行下列命令以還原您專案的套件:Run the following command to restore packages for your project:

     dotnet restore
  3. 將名為 ConnectionStrings:AppConfig 的祕密新增至祕密管理員。Add a secret named ConnectionStrings:AppConfig to Secret Manager.

    此祕密會包含用來存取應用程式設定存放區的連接字串。This secret contains the connection string to access your app configuration store. 請以應用程式設定存放區的連接字串取代下列命令中的值。Replace the value in the following command with the connection string for your app configuration store.

    此命令必須在和 .csproj 檔案相同的目錄中執行。This command must be executed in the same directory as the .csproj file.

     dotnet user-secrets set ConnectionStrings:AppConfig <your_connection_string>


    請以引號括住連接字串,否則某些殼層會截斷連接字串。Some shells will truncate the connection string unless it is 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 App Service 時,您會使用 App Service 中的應用程式設定連接字串,而不會使用祕密管理員來儲存連接字串。When the app is deployed to Azure App Service, for example, you use an application setting Connection Strings in App Service instead of with Secret Manager to store the connection string.

    此祕密可使用設定 API 來存取。This secret is accessed with the configuration API. 在所有支援的平台上,組態 API 的組態名稱中都適用冒號 (:)。A colon (:) works in the configuration name with the configuration API on all supported platforms. 請參閱取決於環境的組態See Configuration by environment.

  4. 開啟 Program.cs ,並將參考新增至 .NET Core 應用程式組態提供者。Open Program.cs, and add a reference to the .NET Core App Configuration provider.

    using Microsoft.Extensions.Configuration.AzureAppConfiguration;
  5. 藉由呼叫 config.AddAzureAppConfiguration() 方法將 CreateWebHostBuilder 方法更新為使用應用程式設定。Update the CreateWebHostBuilder method to use App Configuration by calling the config.AddAzureAppConfiguration() method.

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            .ConfigureAppConfiguration((hostingContext, config) =>
                var settings = config.Build();
  6. 開啟 Views > Home 目錄中的 Index.cshtml ,並將其內容更換為下列程式碼:Open Index.cshtml in the Views > Home directory, and replace its content with the following code:

    @using Microsoft.Extensions.Configuration
    @inject IConfiguration Configuration
        body {
            background-color: @Configuration["TestApp:Settings:BackgroundColor"]
        h1 {
            color: @Configuration["TestApp:Settings:FontColor"];
            font-size: @Configuration["TestApp:Settings:FontSize"];
  7. 開啟 Views > Shared 目錄中的 _Layout.cshtml ,並將其內容更換為下列程式碼:Open _Layout.cshtml in the Views > Shared directory, and replace its content with the following code:

    <!DOCTYPE html>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>@ViewData["Title"] - hello_world</title>
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="~/css/site.css" />
        <div class="container body-content">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
        @RenderSection("Scripts", required: false)

於本機建置並執行應用程式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
  2. 建置成功完成後,請執行下列命令以在本機執行 Web 應用程式:After the build successfully completes, run the following command to run the web app locally:

     dotnet run
  3. 開啟瀏覽器視窗,並前往 http://localhost:5000 (這是本機所裝載 Web 應用程式的預設 URL)。Open a browser window, and go to http://localhost:5000, which is the default URL for the web app hosted locally.

清除資源Clean up resources

如果您打算繼續進行下一個教學課程,請保留在此快速入門中所建立的資源。If you plan to continue to the next tutorial, keep the resources you created in this quickstart. 您可以在下一個教學課程中重複使用這些資源。You can reuse them in the next tutorial.

如果您已完成快速入門範例應用程式,請刪除在此快速入門中所建立的 Azure 資源以避免衍生費用。If you're finished with the quickstart sample application, delete the Azure resources you created in this quickstart 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 hosting this sample inside a resource group that contains 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. 本快速入門的指示是使用名為 AppConfigTestResources 的資源群組。The instructions for this quickstart used a resource group named AppConfigTestResources.
  3. 在結果清單中選取資源群組,並以滑鼠右鍵按一下資料列,或使用省略符號 ( ... ) 按鈕來開啟快顯功能表。In the result list, select the resource group, and either right-click the row or use the ellipsis (...) button to open the context menu.
  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 quickstart, you created a new app configuration store and used it with an ASP.NET Core web app via the App Configuration provider. 若要深入了解如何使用應用程式組態,請繼續進行下一個教學課程,其中會示範如何將 Web 應用程式設定為以動態方式重新整理設定。To learn more about how to use App Configuration, continue to the next tutorial that demonstrates how to configure your web app to dynamically refresh configuration settings.