Nota
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
本文介绍如何在持续集成和持续部署系统中使用来自 Azure 应用程序配置的数据。
如果你有一个 Azure DevOps 管道,则可以从应用程序配置提取键值,并将其设置为任务变量。 Azure 应用程序配置 DevOps 扩展是可以提供此功能的加载项模块。 获取此模块,并参阅使用 Azure Pipelines 从应用程序配置中导出设置,获取在 Azure Pipelines 中使用它的说明。
如果应用程序依赖于 Azure 应用程序配置并且不可访问,则应用程序可能无法运行。 通过将配置数据打包到与应用程序一起部署并在应用程序启动期间本地加载的文件中来提高应用程序的复原能力。 此方法可保证应用程序在启动时具有默认设置值。 当应用程序配置存储区可用时,这些值将被应用程序配置存储区中的任何较新的更改覆盖。
使用 Azure 应用程序配置的导出功能,可以将当前配置数据的检索过程自动化为单个文件。 然后,可以将此文件嵌入到持续集成和持续部署 (CI/CD) 管道的生成或部署步骤中。
下面的示例演示如何将应用程序配置数据包含在快速入门中引入的 Web 应用程序的生成步骤中。 在继续操作之前,请先完成使用应用程序配置创建 ASP.NET Core 应用。
你可以使用任何代码编辑器执行本教程中的步骤。 Visual Studio Code 是 Windows、macOS 和 Linux 平台上提供的一个卓越选项。
如果在本地生成,请下载并安装 Azure CLI(如果尚未安装)。
打开 .csproj 文件,然后添加以下脚本:
<Target Name="Export file" AfterTargets="Build"> <Message Text="Export the configurations to a temp file. " /> <Exec WorkingDirectory="$(MSBuildProjectDirectory)" Condition="$(ConnectionString) != ''" Command="az appconfig kv export -d file --path $(OutDir)\azureappconfig.json --format json --separator : --connection-string $(ConnectionString)" /> </Target>
打开 Program.cs 并更新
CreateWebHostBuilder
方法以通过调用config.AddJsonFile()
方法使用导出的 JSON 文件。 此外,添加System.Reflection
命名空间。public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { var directory = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var settings = config.Build(); config.AddJsonFile(Path.Combine(directory, "azureappconfig.json")); config.AddAzureAppConfiguration(settings["ConnectionStrings:AppConfig"]); }) .UseStartup<Startup>();
设置名为“ConnectionString”的环境变量,并将其设置为应用程序配置存储区的访问密钥。
如果使用 Linux,请运行以下命令:
export ConnectionString='<connection-string-of-your-app-configuration-store>'
要通过使用 .NET CLI 生成应用,请在命令 Shell 中运行以下命令:
dotnet build
生成成功完成后,请运行以下命令以在本地运行 Web 应用:
dotnet run
启动浏览器窗口并转到
http://localhost:5000
,即本地托管的 Web 应用的默认 URL。
在本教程中,导出了要在部署管道中使用的 Azure 应用程序配置数据。 若要了解有关如何使用应用程序配置的更多信息,请继续阅读 Azure CLI 示例。