Pரத*_*ீப் 8 c# azure azure-functions
我试图从local.settings.json文件中检索自定义设置.示例我正在尝试读取以下local.settings.json文件中的表列表
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true",
"TableList": "TestTableName1,TestTableName2"
}
}
Run Code Online (Sandbox Code Playgroud)
使用以下代码阅读它
string tableslist = ConfigurationManager.AppSettings["TableList"];
Run Code Online (Sandbox Code Playgroud)
并且它有效,但我在一些地方读过,这只适用于本地调试,在生产环境中部署之后可能无效.有人能指出我如何以正确的方式做到这一点?或者问题仅适用于连接字符串相关的设置?
Jer*_*Liu 15
@Kirk和@Slava帮助你摆脱困惑.只需添加一些细节供您参考.
默认情况下,发布既不会将local.settings.json上载到Azure,也不会基于该本地文件对应用程序设置进行修改,因此我们需要在Azure门户上手动更新它们.我们也可以在VS发布面板上执行此操作.(如果我们需要在发布之前更改设置,请先创建配置文件.)
关于如何在应用程序设置中获取参数,需要注意的一点ConfigurationManager是v2函数(运行时测试版)不再支持,可能只会获得null或异常.对于v1函数(运行时~1),它仍然有效.
对于v1功能
要建议在Azure上(也在Valueslocal.settings.json中)读取应用程序设置System.Environment.GetEnvironmentVariable($"{parameterName}").
转到连接字符串,遗憾的是GetEnvironmentVariable仅适用于Azure,因为连接字符串(ConnectionStrings在local.settings.json中)未导入到环境变量中.所以我们需要ConfigurationManager,它可以在Azure和本地环境中运行.当然它也可以读取应用程序设置.
对于v2功能,应用程序设置和连接字符串有两种选择.
一种是使用GetEnvironmentVariable.我们可以在Azure上引用此列表中的连接字符串的前缀.
// Get Application settings
var appParameter= "AzureWebJobsStorage";
System.Environment.GetEnvironmentVariable($"{appParameter}");
// Get Connection strings(put local and Azure env together)
var connParameter= "MySqlAzureConnection";
var Prefix = "SQLAZURECONNSTR_";
var connectionString = System.Environment.GetEnvironmentVariable($"ConnectionStrings:{connParameter}");
if(string.IsNullOrEmpty(connectionString )){
connectionString = System.Environment.GetEnvironmentVariable($"{Prefix}{connParameter}");
}
Run Code Online (Sandbox Code Playgroud)
另一个是使用ConfigurationBuilder.添加ExecutionContext参数,用于定位功能app目录.
[FunctionName("FunctionName")]
public static void Run(...,ExecutionContext context)
{
//"Values" and "Connection" sections are injected into EnvironmentVariables automatically hence we don't need to load Json file again.
//Hence SetBasePath and AddJsonFile are only necessary if you have some custom settings(e.g. nested Json rather than key-value pairs) outside those two sections. It's recommended to put those setting to another file if we need to publish them.
//Note that Function binding settings(e.g. Storage Connection String) must be EnvironmentVariables, i.e. must be stored in "Values" section.
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
// Get Application Settings
var appParameter= "AzureWebJobsStorage";
string appsetting = config[$"{appParameter}"];
// Get Connection strings
var connParameter= "MySqlAzureConnection";
string connectionString = config.GetConnectionString($"{connParameter}");
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
8581 次 |
| 最近记录: |