您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:向 Azure Functions 应用添加功能标志Quickstart: Add feature flags to an Azure Functions app

在该快速入门中,你将创建一个 Azure Functions 应用并在其中使用功能标志。In this quickstart, you create an Azure Functions app and use feature flags in it. 可使用 Azure 应用程序配置中的功能管理集中存储所有功能标志并控制其状态。You use the feature management from Azure App Configuration to centrally store all your feature flags and control their states.

.NET 功能管理库使用功能标志支持扩展该框架。The .NET Feature Management libraries extend the framework with feature flag support. 这些库在 .NET 配置系统的基础上构建。These libraries are built on top of the .NET configuration system. 它们通过其 .NET 配置提供程序与应用程序配置集成。They integrate with App Configuration through its .NET configuration provider.

先决条件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. 在“搜索市场”框中,输入“应用配置”,然后选择 EnterIn 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 美国中部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.
    定价层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. 选择“功能管理器” > “+添加”以添加名为 Beta 的功能标志。 Select Feature Manager > +Add to add a feature flag called Beta.

    启用名为 Beta 的功能标志Enable feature flag named Beta

    暂时不定义 labelDescriptionLeave label and Description undefined for now.

  2. 选择“应用” 以保存新功能标志。Select Apply to save the new feature flag.

创建 Functions 应用Create a Functions app

Visual Studio 中的 Azure Functions 项目模板创建了一个项目,该项目可发布到 Azure 中的函数应用。The Azure Functions project template in Visual Studio creates a project that you can publish to a function app in Azure. 可使用函数应用将函数分组为逻辑单元,以便更轻松地管理、部署、缩放和共享资源。You can use a function app to group functions as a logical unit for easier management, deployment, scaling, and sharing of resources.

  1. 在 Visual Studio 菜单中,选择“文件” > “新建” > “项目”。From the Visual Studio menu, select File > New > Project.

  2. 在“创建新项目”中,在搜索框中输入“functions”,选择“Azure Functions”模板,然后选择“下一步”。In Create a new project, enter functions in the search box, choose the Azure Functions template, and then select Next.

  3. 在“配置新项目”中,输入项目的“项目名称”,然后选择“创建”。In Configure your new project, enter a Project name for your project, and then select Create. 函数应用名称必须可以充当 C# 命名空间,因此请勿使用下划线、连字符或任何其他的非字母数字字符。The function app name must be valid as a C# namespace, so don't use underscores, hyphens, or any other nonalphanumeric characters.

  4. 对于“创建新的 Azure Functions 应用程序”设置,请使用下表中的值:For the Create a new Azure Functions application settings, use the values in the following table:

    设置Setting Value 说明Description
    Functions 运行时Functions runtime Azure Functions v3
    (.NET Core)
    Azure Functions v3
    (.NET Core)
    此值会创建使用 Azure Functions 的版本 3.x 运行时(支持 .NET Core 3.x)的函数项目。This value creates a function project that uses the version 3.x runtime of Azure Functions, which supports .NET Core 3.x. Azure Functions 1.x 支持 .NET Framework。Azure Functions 1.x supports the .NET Framework. 有关详细信息,请参阅 Azure Functions 运行时版本概述For more information, see Azure Functions runtime versions overview.
    函数模板Function template HTTP 触发器HTTP trigger 此值会创建由 HTTP 请求触发的函数。This value creates a function triggered by an HTTP request.
    存储帐户(AzureWebJobsStorage)Storage account (AzureWebJobsStorage) 存储模拟器Storage emulator 由于 Azure 函数需要存储帐户,因此在将项目发布到 Azure 时会分配或创建一个存储帐户。Because an Azure Function requires a storage account, one is assigned or created when you publish your project to Azure. HTTP 触发器不使用 Azure 存储帐户连接字符串;所有其他触发器类型需要有效的 Azure 存储帐户连接字符串。An HTTP trigger doesn't use an Azure Storage account connection string; all other trigger types require a valid Azure Storage account connection string.
    授权级别Authorization level 匿名Anonymous 在未提供密钥的情况下,任何客户端都可以触发创建的函数。The created function can be triggered by any client without providing a key. 通过此授权设置可以轻松测试新函数。This authorization setting makes it easy to test your new function. 有关密钥和授权的详细信息,请参阅授权密钥HTTP 和 Webhook 绑定For more information about keys and authorization, see Authorization keys and HTTP and webhook bindings.

    Azure Functions 项目设置

    请确保将“授权级别”设置为“匿名”。 Make sure you set the Authorization level to Anonymous. 如果选择默认级别的 函数,需要在请求中提供 函数密钥才能访问函数终结点。If you choose the default level of Function, you're required to present the function key in requests to access your function endpoint.

  5. 选择“创建”以创建函数项目和 HTTP 触发器函数。Select Create to create the function project and HTTP trigger function.

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

此项目将 .NET Azure Functions 中使用依赖项注入This project will use dependency injection in .NET Azure Functions. 它将 Azure 应用程序配置添加为存储功能标志的额外配置源。It adds Azure App Configuration as an extra configuration source where your feature flags are stored.

  1. 右键单击项目,然后选择“管理 NuGet 包” 。Right-click your project, and select Manage NuGet Packages. 在“浏览”选项卡中,搜索以下 NuGet 包并将其添加到项目中。On the Browse tab, search for and add following NuGet packages to your project.

  2. 使用以下代码添加新文件 Startup.cs。Add a new file, Startup.cs, with the following code. 它定义了一个名为 Startup 的类,该类实现了 FunctionsStartup 抽象类。It defines a class named Startup that implements the FunctionsStartup abstract class. 程序集属性用于指定 Azure Functions 启动期间使用的类型名称。An assembly attribute is used to specify the type name used during Azure Functions startup.

    using System;
    using Microsoft.Azure.Functions.Extensions.DependencyInjection;
    using Microsoft.Extensions.Configuration;
    using Microsoft.FeatureManagement;
    
    [assembly: FunctionsStartup(typeof(FunctionApp.Startup))]
    
    namespace FunctionApp
    {
        class Startup : FunctionsStartup
        {
            public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
            {
            }
    
            public override void Configure(IFunctionsHostBuilder builder)
            {
            }
        }
    }
    
  3. 更新 ConfigureAppConfiguration 方法,并通过调用 AddAzureAppConfiguration() 将 Azure 应用程序配置提供程序添加为额外的配置源。Update the ConfigureAppConfiguration method, and add Azure App Configuration provider as an extra configuration source by calling AddAzureAppConfiguration().

    UseFeatureFlags() 方法告知提供程序加载功能标志。The UseFeatureFlags() method tells the provider to load feature flags. 在重新检查更改之前,所有功能标志的默认缓存过期时间为 30 秒。All feature flags have a default cache expiration of 30 seconds before rechecking for changes. 可以通过设置传递给 UseFeatureFlags 方法的 FeatureFlagsOptions.CacheExpirationInterval 属性来更新过期时间间隔。The expiration interval can be updated by setting the FeatureFlagsOptions.CacheExpirationInterval property passed to the UseFeatureFlags method.

    public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
    {
        builder.ConfigurationBuilder.AddAzureAppConfiguration(options =>
        {
            options.Connect(Environment.GetEnvironmentVariable("ConnectionString"))
                   .Select("_")
                   .UseFeatureFlags();
        });
    }
    

    提示

    如果不想将除功能标志以外的任何配置加载到应用程序中,可以调用 Select("_") 只加载不存在的伪键“”。If you don't want any configuration other than feature flags to be loaded to your application, you can call Select("_") to only load a nonexisting dummy key "". 默认情况下,如果未调用 Select 方法,则将加载应用程序配置存储中的所有配置键值。By default, all configuration key-values in your App Configuration store will be loaded if no Select method is called.

  4. 更新 Configure 方法,通过依赖项注入使 Azure 应用程序配置服务和功能管理器可用。Update the Configure method to make Azure App Configuration services and feature manager available through dependency injection.

    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddAzureAppConfiguration();
        builder.Services.AddFeatureManagement();
    }
    
  5. 打开 Function1.cs,并添加以下命名空间。Open Function1.cs, and add the following namespaces.

    using System.Linq;
    using Microsoft.FeatureManagement;
    using Microsoft.Extensions.Configuration.AzureAppConfiguration;
    

    添加一个构造函数,用于通过依赖项注入获得 _featureManagerSnapshotIConfigurationRefresherProvider 实例。Add a constructor used to obtain instances of _featureManagerSnapshot and IConfigurationRefresherProvider through dependency injection. IConfigurationRefresherProvider 中,你可以获得 IConfigurationRefresher 的实例。From the IConfigurationRefresherProvider, you can obtain the instance of IConfigurationRefresher.

    private readonly IFeatureManagerSnapshot _featureManagerSnapshot;
    private readonly IConfigurationRefresher _configurationRefresher;
    
    public Function1(IFeatureManagerSnapshot featureManagerSnapshot, IConfigurationRefresherProvider refresherProvider)
    {
        _featureManagerSnapshot = featureManagerSnapshot;
        _configurationRefresher = refresherProvider.Refreshers.First();
    }
    
  6. 更新 Run 方法,根据功能标志的状态更改显示的消息的值。Update the Run method to change the value of the displayed message depending on the state of the feature flag.

    在函数调用开始时调用 TryRefreshAsync 方法以刷新功能标志。The TryRefreshAsync method is called at the beginning of the Functions call to refresh feature flags. 如果未到达缓存过期时间范围,则将是一个 no-op 操作。It will be a no-op if the cache expiration time window isn't reached. 如果希望在不阻止当前函数调用的情况下刷新功能标志,请删除 await 运算符。Remove the await operator if you prefer the feature flags to be refreshed without blocking the current Functions call. 在这种情况下,以后的函数调用将获得更新的值。In that case, later Functions calls will get updated value.

    [FunctionName("Function1")]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");
    
        await _configurationRefresher.TryRefreshAsync();
    
        string message = await _featureManagerSnapshot.IsEnabledAsync("Beta")
                ? "The Feature Flag 'Beta' is turned ON"
                : "The Feature Flag 'Beta' is turned OFF";
    
        return (ActionResult)new OkObjectResult(message);
    }
    

在本地测试函数Test the function locally

  1. 设置一个名为 ConnectionString 的环境变量,其中值是之前在“访问密钥”下的应用程序配置存储中检索到的连接字符串 。Set an environment variable named ConnectionString, where the value is the connection string you retrieved earlier in your App Configuration store under Access Keys. 如果使用 Windows 命令提示符,则请运行以下命令并重启命令提示符,这样更改才会生效:If you use the Windows command prompt, run the following command and restart the command prompt to allow the change to take effect:

        setx ConnectionString "connection-string-of-your-app-configuration-store"
    

    如果使用 Windows PowerShell,请运行以下命令:If you use Windows PowerShell, run the following command:

        $Env:ConnectionString = "connection-string-of-your-app-configuration-store"
    

    如果使用 macOS 或 Linux,则请运行以下命令:If you use macOS or Linux, run the following command:

        export ConnectionString='connection-string-of-your-app-configuration-store'
    
  2. 按 F5 测试函数。Press F5 to test your function. 如果系统提示,请按 Visual Studio 的请求下载和安装 Azure Functions Core (CLI) 工具。If prompted, accept the request from Visual Studio to download and install Azure Functions Core (CLI) tools. 你还需要启用防火墙例外,这样工具才能处理 HTTP 请求。You might also need to enable a firewall exception so that the tools can handle HTTP requests.

  3. 从 Azure Functions 运行时输出复制函数的 URL。Copy the URL of your function from the Azure Functions runtime output.

    在 VS 中的函数调试快速入门

  4. 将 HTTP 请求的 URL 粘贴到浏览器的地址栏。Paste the URL for the HTTP request into your browser's address bar. 下图显示了指出功能标志 Beta 已被禁用的响应。The following image shows the response indicating that the feature flag Beta is disabled.

    已禁用快速入门函数功能标志

  5. 登录 Azure 门户Sign in to the Azure portal. 选择“所有资源”,然后选择你创建的应用程序配置存储区。Select All resources, and select the App Configuration store that you created.

  6. 选择“功能管理器”,将“Beta”密钥的状态更改为“启用”。Select Feature manager, and change the state of the Beta key to On.

  7. 多次刷新浏览器。Refresh the browser a few times. 当缓存的功能标志在 30 秒后过期时,页面应该已经更改,以指示功能标志 Beta 已打开,如下图所示。When the cached feature flag expires after 30 seconds, the page should have changed to indicate the feature flag Beta is turned on, as shown in the image below.

    已启用快速入门函数功能标志

备注

本教程中使用的示例代码可从 Azure 应用程序配置 GitHub 存储库下载。The example code used in this tutorial can be downloaded from the Azure App Configuration GitHub repo.

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

在本快速入门中,你创建了一个功能标志,并通过 Microsoft.FeatureManagement 库将它用于 Azure Functions 应用。In this quickstart, you created a feature flag and used it with an Azure Functions app via the Microsoft.FeatureManagement library.