我正在尝试使用 dotnet-isolated 将旧版 .NET Framework 的某些功能迁移到 Azure Function Apps V4。我可以触发应用程序,但是 Azure 门户中定义的应用程序设置和连接字符串无法通过 ConfigurationManager
获得。该应用程序的其他部分托管在应用服务上,并且 ConfigurationManager
在那里工作正常。
有很多关于 IConfiguration
和 local.settings.json
的信息,但这不是我可以使用的。有很多代码依赖于 ConfigurationManager.AppSettings
和 ConfigurationManager.ConnectionStrings
,它们需要保持原样工作。 EF6 就是一个示例,但也有其他自定义代码。
我已在 Azure 门户中定义了应用设置和连接字符串。我可以在 Kudu“环境” View 中将它们视为环境变量,如下所示:
APPSETTING_my_setting="myvalue"
SQLAZURECONNSTR_my_connection_string="foo=bar"
我本以为这会“正常工作”,但事实并非如此。我是否认为它是错误的,或者我可以做什么来说服 ConfigurationManager
使用这些设置?
最佳答案
我已经能够通过配置生成器实现这一目标; .NET 4.7 中引入的一项功能。我使用环境配置生成器来实现与常规应用服务相同的行为。请注意,以下代码仅适用于 SqlAzure 类型连接字符串,但可以轻松调整以支持所有连接字符串类型。
项目文件:
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="Microsoft.Configuration.ConfigurationBuilders.Environment" Version="3.0.0" />
</ItemGroup>
</Project>
配置文件:
<configuration>
<configSections>
<section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</configSections>
<configBuilders>
<builders>
<add name="AppSetting" prefix="APPSETTING_" stripPrefix="true" type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Environment" />
<add name="SqlAzure" prefix="SQLAZURECONNSTR_" stripPrefix="true" type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Environment" />
</builders>
</configBuilders>
<connectionStrings configBuilders="SqlAzure">
<add name="my_connection_string" providerName="System.Data.SqlClient" connectionString="" />
</connectionStrings>
<appSettings configBuilders="AppSetting">
<add name="my_setting" value="" />
</appSettings>
</configuration>
关于Azure Function Apps V4 上的 .NET Framework(dotnet 隔离): ConfigurationManager not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76468377/