c# - CloudConfigurationManager 未从 app.config 中获取 ApplicationSettings

标签 c# azure configuration-files

我有一个包含一些 Azure 帮助程序类的库。在这些帮助程序类中,我获取了 Azure 帐户名和 key 等设置。在 Azure 中运行时,这些设置是从云配置文件 (cscfg) 中获取的。这一切都运行良好。

为了在 Azure 之外(特别是 RoleEnvironment)对这些类进行单元测试,我在单元测试项目中创建了相同变量名称的设置。这些实际上保存在 app.config 文件中,并通过位于我的测试项目的属性部分下的设置部分进行编辑。我决定使用 CloudConfigurationManager 类,而不是创建自己的从 web.config/app.config 设置中抽象云配置设置的方法。但是,当我运行单元测试时,没有选择任何设置,因此我只是得到空值。但是,如果我将 app.config 文件更改为使用下面“appSettings”格式的设置,那么我确实会获得有效值。这样做的缺点是我无法再使用 Visual Studio 中的设置编辑器页面编辑我的设置。

所以我的问题是我做错了什么,还是这是云配置管理器的限制,它只能获取手动添加的 appSettings,而不能获取使用编辑器添加的 applicationSettings?

<appSettings>
    <add key="Foo" value="MySettingValue"/>
</appSettings>

以上有效,而以下无效:

<applicationSettings>
    <ComponentsTest.Properties.Settings>
      <setting name="Foo" serializeAs="String">
        <value>MySettingValue</value>
      </setting>
    </ComponentsTest.Properties.Settings>  
</applicationSettings>

最佳答案

CloudConfigurationManager 仅支持 web.config/app.config 的 AppSettings 部分,并且如果 Azure 配置中缺少该设置,将尝试从此处读取值。该文档指出,如果属性 RoleEnvironment.IsAvailable 为 true(在 Azure 中运行),它不会读取 web.config/app.config,但这是不正确,正如我们在下面的源代码中看到的那样(没有检查 IsAvailable)。

您可以查看source看看会发生什么:

    /// <summary>
    /// Gets a setting with the given name.
    /// </summary>
    /// <param name="name">Setting name.</param>
    /// <returns>Setting value or null if such setting does not exist.</returns>
    internal string GetSetting(string name)
    {
        Debug.Assert(!string.IsNullOrEmpty(name));

        string value = null;

        value = GetValue("ServiceRuntime", name, GetServiceRuntimeSetting);
        if (value == null)
        {
            value = GetValue("ConfigurationManager", name, n => ConfigurationManager.AppSettings[n]);
        }

        return value;
    }

如您所见,只有一次对普通 ConfigurationManager 类的调用,该类仅访问 AppSettings

关于c# - CloudConfigurationManager 未从 app.config 中获取 ApplicationSettings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11611404/

相关文章:

java - Apache commons 配置读取格式为 a.<no>.b 的属性

azure - Web 部署任务失败。目的地无法到达

c# - 如何在 ASP.NET MVC 中设置时区?

c# - 正则表达式查找特殊模式

c# - 在 Windows 窗体应用程序中托管 gRPC 服务

azure - 与旧库相比,新库的 Cosmos DB 速度非常慢

c# - 将位图对象上传到 Azure Blob 存储

c# - 带有单独 .config 文件的 System.Configuration

testing - Testcafe - 如何在报告中设置相对而不是绝对的屏幕截图路径

c# - 单点触控 : Can't create DbParameterCollection?