appSettings和ConfigurationManager.AppSettings问题

时间:2009-04-02 23:46:47

标签: c# asp.net asp.net-mvc

我搜索了网站,虽然我发现了一些非常有用的信息,但我无法弄清楚我的代码是怎么回事。我有以下web.config:

<?xml version="1.0"?>
<configuration>
  <system.web>
  </system.web>

  <system.webServer>
  </system.webServer>

  <appSettings>
    <add key="APIKey" value="23e24c73feed7ca0f6afd876575842de"/>
    <add key="Secret" value="################################"/>
    <add key="Callback" value="http://localhost:55994/"/>
    <add key="Suffix" value="My3Words"/>
  </appSettings>
</configuration>

我已经删除了system.web和system.webServer中的内容,但它是ASP.NET MVC应用程序中生成的默认设置。

我正在尝试访问该部分中的键(这是一个使用FB Connect的简单Facebook应用程序)。

在我的代码中,我有以下一行:

return ConfigurationManager.AppSettings["APIKey"];

它返回null。我无法弄清楚发生了什么。我有必要:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Configuration;

位于我的.cs文件的顶部。我有一个非常强烈的怀疑,键盘后(即在我的大脑中)存在错误,但我无法解决这个问题。有什么想法吗?

8 个答案:

答案 0 :(得分:29)

您是否尝试过使用WebConfigurationManager

return System.Web.Configuration.WebConfigurationManager.AppSettings["APIKey"];

这是在Web应用程序中使用配置文件的首选选项 - 它处理嵌套配置文件等内容。

答案 1 :(得分:9)

Visual Studio为MVC创建2个web.config文件。 1位于根目录,另一位位于Views文件夹中。

答案 2 :(得分:4)

您确定使用的是正确的Web.Config文件吗?您可能希望使用应用程序根目录中的那个,而不是Views目录中的那个。

ASP.NET MVC and two Web.config files

答案 3 :(得分:1)

检查以确保web.config文件的Build Action为“None”。如果构建操作是“嵌入式资源”,我已经看到了这个问题。

答案 4 :(得分:1)

您的machine.config是否具有必需的AppSettings部分。它应该看起来像(版本号会有所不同):

<configuration>
   <configSections>
       <section name="appSettings"
          type="System.Configuration.NameValueFileSectionHandler, System,          Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
   </configSections>
</configuration>

您确定使用的是正确的web.config吗? ConfigurationManager.AppSettings.Settings看起来像什么?

答案 5 :(得分:0)

我打赌你在编写时使用正确的语法来访问它们:ConfigurationManager.AppSettings [“Key1”];

尝试使用此配置格式

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<appSettings>
    <add key="Key1" value="Val1"/>
    <add key="Key2" value="Val2"/>
</appSettings>
<connectionStrings>
    ......
    ......
</connectionStrings>
<system.web>
    <sessionState mode="InProc" timeout="20"/>
    <authorization>
        ......
    </authorization>

    <pages>
        <namespaces>
            <add namespace="System.Data"/>
            <add namespace="System.Data.SqlClient"/>
            <add namespace="System.IO"/>
        </namespaces>
    </pages>
    <customErrors mode="Off"/>
    <compilation debug="true"/></system.web>
</configuration>

答案 6 :(得分:0)

我的解决方案中有两个项目我首先在类库项目中添加app.config文件,所有实例都是从控制台应用程序调用的,我在类lib项目的配置文件中添加了这些条目

<appSettings> 
<add key="userName" value="user2" /> 
<add key="emilsLimit" value="50" /> 
</appSettings>

当我在类库项目中的类中获取这些异常时抛出null异常但是当我从类库项目中删除app.config并在Console项目中添加它时它工作。欢呼

注意:类lib项目引用已添加到控制台

答案 7 :(得分:-1)

你试过了吗?

return ConfigurationManager.AppSettings.Get("APIKey");