App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the Values collection in the local.settings.json file. In both environments, local and Azure, GetEnvironmentVariable("") retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains { "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }.
The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values, but we recommend that you use GetEnvironmentVariable as shown here.
没有说明为什么这是推荐的方式。
- 它有性能优势吗?
- 是否存在从 AppSettings 读取会导致空值的情况?
- 只是为了兼容不同的配置格式(即 json、xml 等)吗?
或者我只是接受这是生活的事实而不知道为什么?
最佳答案
Does it have performance advantages?
我会说,根据我的测试,通常是这样。 GetEnvironmentVariable
比 ConfigurationManager
快一点,在我的电脑上(100k 次),它的平均执行时间短了大约 20μs,在 Azure(B1 应用服务计划,10k 次)上是约短12μs。这是一个统计结论,因为 ConfigurationManager
有时会更快。
Is there is an instance where reading from AppSettings would result in an empty value?
如果要读取的值按预期设置,则可能只有一种情况我们使用 ConfigurationManager
获取 null - 在 v2 函数中,它不再有用。
Is it just for compatibility with different configuration formats (i.e., json, xml, etc)?
GetEnvironmentVariable
没有这样的能力,并且没有格式兼容性的要求。根据设计,Azure 函数在本地开发中从 local.settings.json 获取配置,当函数主机启动时,Values
中的应用设置将导入到当前进程的环境变量中。因此无需考虑格式。
总而言之,GetEnvironmentVariable
是
- 简洁——无需导入
System.Configuration
程序集即可使用ConfigurationManager
。 - 通用 - 适用于 v1 和 v2、本地和 Azure 环境。(不包括 local.settings.json 中的
ConnectionStrings
)。 - 更快 - 可能不太可靠,我使用简单的循环来重复触发秒表来测量(禁用所有日志)。
当然,我们仍然可以在 v1 函数中利用 ConfigurationManager
,如果我们想在本地获取 ConnectionStrings
,我们就必须使用它。
关于c# - 为什么在读取 Azure Functions 中的环境变量时建议使用 GetEnvironmentVariable 而不是 AppSettings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51808517/