【问题标题】:Problem calling a second .config for keys in C#在 C# 中为键调用第二个 .config 时出现问题
【发布时间】:2021-02-19 04:28:44
【问题描述】:

我需要第二个 .config 来管理很多密钥。我尝试使用

  <configSections>
         <section name="apiConnection" type="CustomConfig.apiConnectionSection, CustomConfig" />
  </configSections>
  <apiConnection configSource ="ApiConnection.config"/>

“ApiConnection.config”是我用于管理密钥的 .config 文件,但这不起作用。 然后我尝试了 appSettings 中的“文件”属性。

<appSettings file="ApiConnection.config">   

这也不起作用。我试过了:

../ApiConnection.config

~/ApiConnection.config

但没什么... 有什么想法吗?

程序没有中断,只是在我尝试使用 ConfigurationManager 时没有显示密钥。

https://i.stack.imgur.com/6xHK2.png

&lt;img src= https://i.stack.imgur.com/6xHK2.png/&gt;

编辑

我的文件位于根路径(带有 web.config)

文件看起来像

<?xml version="1.0" encoding="utf-8"?>
<appSettings>
  <add key="Secret" value="z8xyHkN3Eju2TS9u-4MXeI2AbZiuTsF7xYJcjIJ" />
  <add key="Audience" value="keyforms"/>
</appSettings>

【问题讨论】:

  • 很难从上面有限的样本中看出,但你可能试图在过高的水平上外化。看看这个堆栈溢出问题,看看它是否有帮助。 stackoverflow.com/questions/1562679/…
  • 感谢您的帮助!我在我给出的第一个例子中尝试了这种方式。 (我将对其进行编辑以便很好理解)。
  • 不幸的是,这些编辑确实有很大帮助。我不明白为什么这不起作用。您是否从 IIS 收到错误消息?
  • nop,当我尝试使用 ConfigurationManager.AppSettings 时不会显示密钥。 (空列表)

标签: c# xml web-config app-config relative-path


【解决方案1】:

好的,根据您的最后评论,我想我知道您的问题是什么。

此代码正在创建一个名为 apiConnection 的新配置部分。

  <configSections>
         <section name="apiConnection" type="CustomConfig.apiConnectionSection, CustomConfig" />
  </configSections>
  <apiConnection configSource ="ApiConnection.config"/>

此部分的值不会包含在应用设置中。所以你将无法通过

ConfigurationManager.AppSettings

您需要以不同的方式访问它。现在,确切的方式将取决于您对 CustomConfig.apiConnectionSection 和 CustomConfig 的实现。我会搜索您的代码以找到定义其工作方式的类。

此示例说明如何从自定义配置部分 SecureAppSettings 中提取值,该部分以与 AppSettings 相同的方式使用 NameValueCollection。您必须进行一些挖掘才能确定需要使用哪些类型。

NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings");
string userName = section["userName"];

【讨论】:

    猜你喜欢
    • 2011-02-26
    • 2022-08-18
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 2017-07-17
    • 1970-01-01
    相关资源
    最近更新 更多