【问题标题】:Pull email address from appSettings从 appSettings 中提取电子邮件地址
【发布时间】:2011-07-06 00:28:42
【问题描述】:

我正在尝试从 app.config 文件的 appSettings 部分提取电子邮件地址。每次我运行测试时,reportRecipients 都是 Null。谁能看到我做错了什么?

  <appSettings>
    <add key="Overdue_Report_Recipients" value="myemail@email.com"/>
  </appSettings>

string reportRecipients = ConfigurationManager.AppSettings["Overdue_Report_Recipients"];

谢谢

编辑: 这适用于不是 Web 应用程序的项目。它是解决方案的一部分,其中大多数项目都是 Web 应用程序,但这个特定的项目是一项服务。很抱歉与我已删除它的 asp.net 标签混淆。

我在应用设置中存储了另一个值,我可以从中获取数据

<add key="Sweeper_Notify_When_None_Overdue" value="false"/> 

bool sendWhenNoneOverdue = 
                Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["Sweeper_Notify_When_None_Overdue"]);

回答: 我在一个单独的项目中运行我的测试,并且测试是从测试项目中的配置文件而不是我正在测试的项目中的 app.config 读取的。 我必须将设置复制到测试项目中的配置中,然后测试才起作用。

【问题讨论】:

  • 你的 web.config 中有这个,对吧?在“配置”->“configSections”下???
  • @Zachary,我同意我认为 Ronald 可能没有 元素。
  • 如果你使用索引 0 而不是键,你会得到什么?
  • 可以在 web.config 中指定要使用的文件,例如:
  • 它在 App.Config 而不是 web.config

标签: c# web-config app-config


【解决方案1】:

使用 ASP.NET,&lt;appSettings&gt; 部分应位于 web.config 文件中,而不是您所描述的 app.config。

当您从 asp.net 网站或 Web 应用程序中调用 ConfigurationManager.AppSettings["some key"] 时,它将在 web.config 文件中查找。如果您将密钥存储在 app.config 文件中,这就是它返回 null 的原因。

如果您愿意,您也可以将应用设置存储在与 web.config 不同的文件中。为此,请在您的 web.config 中放置:

<configuration>
  <appSettings file="someSettingsFile.config" />
  ...
</configuration>

然后在 someSettingsFile.config 中:

<appSettings>
    <add key="Overdue_Report_Recipients" value="myemail@email.com"/>
</appSettings>

我怀疑您只是将appSettings 的位置放错了文件中。只需将其移至您的 web.config 即可。

【讨论】:

  • 有没有办法使用 app.config 文件做到这一点?
  • 您可以尝试引用 app.config 文件作为 appSettings 部分的外部引用,就像在您的 web.config &lt;appSettings file="app.settings"/&gt; 中一样,但我不确定后果。我认为应该工作。 ASP.NET 将始终首先查看 web.config,因此如果您想为该部分使用单独的文件,file="" 属性是必须的。
【解决方案2】:
var reportRecipients = ConfigurationManager.AppSettings["Overdue_Report_Recipients"].ToString();

更新。

我刚刚在自己的代码中指出,不需要 .ToString() 并且您拥有的应该可以正常工作。

确认一下,web.config 应该类似于;

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="Overdue_Report_Recipients" value="myemail@email.com"/>
  </appSettings>
</configuration>

【讨论】:

  • OP 注意到 app.Settings 文件的使用,但应该将 web.config 用于 ASP.NET 项目。我已经在我的回答中注意到了这一点。
【解决方案3】:

我在一个单独的项目中运行我的测试,并且测试是从测试项目中的配置文件而不是我正在测试的项目中的 app.config 读取的。我必须将设置复制到测试项目中的配置中,然后测试才起作用。

【讨论】:

    猜你喜欢
    • 2016-04-12
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2014-05-26
    • 2020-01-17
    • 2017-10-10
    相关资源
    最近更新 更多