简体   繁体   English

how to read azure app config values in C# startup.cs class in azure function

[英]how to read azure app config values in C# startup.cs class in azure function

I have added key value pair in Azure app Configuration and trying to read it in Startup.cs class file.我在 Azure 应用程序配置中添加了键值对,并尝试在 Startup.cs class 文件中读取它。 Please suggest how to do that.请建议如何做到这一点。

public class Startup : FunctionsStartup
{
    private static readonly string url= "*******************";
   
    public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
    {
        string connectionString=????? //How to get this value from Azure app config
        builder.Services.AddDbContext<DbContext, Context>(
            options => SqlServerDbContextOptionsExtensions.UseSqlServer(options, connectionString));
       builder.ConfigurationBuilder.AddAzureAppConfiguration(url);
    }
}

You need to split out configuration of your configuration from the registration of your application services.您需要将配置的配置与应用程序服务的注册分开。 In other words, setup of Azure App Configuration should be done in ConfigureAppConfiguration while the registration of your DbContext should be done from the Configure method.换句话说,Azure App Configuration 的设置应该在ConfigureAppConfiguration中完成,而DbContext的注册应该在Configure方法中完成。 This will allow you to access the Configuration property of the FunctionsHostBuilderContext in the Configure method to retrieve your connection string:这将允许您在Configure方法中访问FunctionsHostBuilderContextConfiguration属性以检索您的连接字符串:

public class Startup : FunctionsStartup
{
    private static readonly string url= "*******************";
   
    public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
    {
        // register AzureAppConfiguration only
        builder.ConfigurationBuilder.AddAzureAppConfiguration(url);
    }

    public override void Configure(IFunctionsHostBuilder builder)
    {
        var context = build.GetContext();
        var config = context.Configuration;

        string connectionString = config["AzureAppConfigKeyName"];
        builder.Services.AddDbContext<DbContext, Context>(
            options => SqlServerDbContextOptionsExtensions.UseSqlServer(options, connectionString)
        );
    }
}

The value you pass to the indexer of the config object is going to depend on what you named your key in Azure App Configuration.您传递给config object 的索引器的值将取决于您在 Azure 应用程序配置中命名您的密钥的名称。 Assuming you called it "DatabaseConnectionString" then that is exactly what you'll pass, ie: config["DatabaseConnectionString"] .假设您将其称为“DatabaseConnectionString”,那么这正是您要传递的内容,即: config["DatabaseConnectionString"]

Prefixes前缀

Azure App Configuration has a few features that can control how the key names are handled by the application, specifically the ability to "Trim Prefixes". Azure 应用程序配置有一些功能可以控制应用程序如何处理键名,特别是“修剪前缀”的能力。 You aren't using that here (since you are just passing the URL) but suppose you had keys in Azure App Configuration such as MyFunction:DatabaseConnectionString .您在这里没有使用它(因为您只是传递 URL),但假设您在 Azure 应用程序配置中有键,例如MyFunction:DatabaseConnectionString By default you would access this using it's full name:默认情况下,您将使用它的全名访问它:

var cs1 = config["MyFunction:DatabaseConnectionString"];
// or
var cs2 = config.GetSection("MyFunction")["DatabaseConnectionString"];

You could however specify the long-form connection options.但是,您可以指定长格式连接选项。 This would allow you to only select keys that begin with that prefix and optionally trim them off:这将只允许您使用以该前缀开头的 select 键,并且可以选择将它们修剪掉:

builder.ConfigurationBuilder.AddAzureAppConfiguration(s => 
{
    s.Connect(url, new DefaultAzureCredential());
    s.Select("MyFunction:*");
    s.TrimKeyPrefix("MyFunction:");
});

Which would now make your connection string available with a shorter key:现在,这将使您的连接字符串可以使用更短的密钥:

string connectionString = config["DatabaseConnectionString"];

This feature is especially useful if you have a lot of different settings in your Azure App Configuration instance and only want to pull in those specifically related to your application (labels can also be used for this purpose).如果您在 Azure 应用程序配置实例中有很多不同的设置并且只想拉入那些与您的应用程序特别相关的设置(标签也可用于此目的),则此功能特别有用。

Azure App Config Connection - Environment Variables Azure 应用程序配置连接 - 环境变量

Finally, a suggestion.最后,提个建议。 Don't store the url or connection details of your Azure App Configuration instance hard-coded in your application.不要将url或 Azure 应用程序配置实例的连接详细信息硬编码在应用程序中。 Make use of environment variables for this.为此使用环境变量。 "Application Settings" in Azure App Service/Azure Functions are automatically added as environment variables to your application. Azure App Service/Azure Functions 中的“应用程序设置”会作为环境变量自动添加到您的应用程序中。

Before ConfigureAppConfiguration has run, a default set of configuration sources has already been added to the context/builder.ConfigureAppConfiguration运行之前,已经将一组默认配置源添加到上下文/构建器中。 These include host.json , appsettings.json , local.settings.json (when running locally) and environment variables.其中包括host.jsonappsettings.jsonlocal.settings.json (在本地运行时)和环境变量。 A "better" way to configure your link to Azure App Configuration is to use this mechanism.配置到 Azure 应用程序配置的链接的“更好”方法是使用此机制。

For example, you can add a FunctionApp Application Setting named AzureAppConfigUrl that contains this value:例如,您可以添加一个名为AzureAppConfigUrl的 FunctionApp 应用程序设置,其中包含以下值:

应用程序设置

Locally you'd add a corresponding entry to your local.settings.json file:本地,您将在 local.settings.json 文件中添加相应的条目:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "AzureAppConfigUrl": "https://your-configuration.azconfig.io"
  }
}

You'd then reference this value when configuring Azure App Configuration.然后,您将在配置 Azure 应用程序配置时引用此值。 Locally it will pull from the JSON file and when running in Azure it will read from the Application Settings (or rather, the environment variables):在本地,它将从 JSON 文件中提取,当在 Azure 中运行时,它将从应用程序设置(或者更确切地说,环境变量)中读取:

public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
{
   var context = build.GetContext();
   var url = context.Configuration["AzureAppConfigUrl"];
   builder.ConfigurationBuilder.AddAzureAppConfiguration(url);
}

ConfigureAppConfiguration method should be used exclusively to configure application's IConfiguration object. ConfigureAppConfiguration方法应专门用于配置应用程序的IConfiguration object。 There is another dedicated method Configure which should be used to configure application itself (eg dependency injection).还有另一种专用方法Configure应该用于配置应用程序本身(例如依赖注入)。

Here is the simple example:这是一个简单的例子:

public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
{
    FunctionsHostBuilderContext context = builder.GetContext();

    builder.ConfigurationBuilder
        .SetBasePath(context.ApplicationRootPath)
        .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables();
}

public override void Configure(IFunctionsHostBuilder builder)
{
    IConfiguration configuration = builder.Services.BuildServiceProvider().GetRequiredService<IConfiguration>();

    // use configuration object 
}

If that doesn't work for you for some reason, you can always fallback to get the value from environmental variables, since settings are added to Environment如果由于某种原因这对您不起作用,您可以随时回退以从环境变量中获取值,因为设置已添加到Environment

Environment.GetEnvironmentVariable("DatabaseConnectionString"))

The doc below walks you through how to use Azure App Configuration in Azure Functions https://docs.microsoft.com/azure/azure-app-configuration/quickstart-azure-functions-csharp下面的文档将引导您了解如何在 Azure 函数https: //docs.microsoft.com/azure/azure-functions 中使用 Azure 应用程序配置

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Azure Function 中引用类库 .dll 文件,是否需要在 Startup.cs 中设置服务? - Referencing class library .dll file in Azure Function, do I need to setup the services in Startup.cs? 通过 Azure 门户中的“身份验证”刀片与 Startup.cs 中的手动保护 Function 应用程序 - Securing Function App via 'Authentication' blade in Azure Portal vs. manually in Startup.cs .net 5 登录到 azure 应用程序服务协议 stream 在 startup.cs 之外不起作用 - .net 5 logging to azure app service protocol stream not working outside startup.cs 连接到 .NET 3.1 中的 Entity Framework Core - Connect to Entity Framework Core in .NET 3.1 Azure Function Project Startup.cs 为什么启动我的Azure Function时没有使用startup.cs文件? - Why is the startup.cs file not being used when I start my Azure Function? 是否可以访问 Startup.cs 中的任何 Azure Function 触发器详细信息/上下文? - Is it possible to access any Azure Function trigger details/context in Startup.cs? 为什么我的 Azure Function 无法在 startup.cs 中正确加载我的环境变量? - Why would my Azure Function not load my environment variables correctly in startup.cs? 在startup.cs上的IIS 8.5配置(Azure webrole) - IIS 8.5 configuration on startup.cs (Azure webrole) 如何将C#MVC5 Global.asax迁移到ASP.NET Core Startup.cs - How to migrate C# MVC5 Global.asax to ASP.NET Core Startup.cs 如何在 Startup.cs 中实例化 singleton class 然后在网络核心中使用? - how to instantiate a singleton class in Startup.cs and then use in net core?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM