[英]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
方法中访问FunctionsHostBuilderContext
的Configuration
属性以检索您的连接字符串:
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"]
。
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 应用程序配置实例中有很多不同的设置并且只想拉入那些与您的应用程序特别相关的设置(标签也可用于此目的),则此功能特别有用。
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.json
、 appsettings.json
、 local.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.