![](/img/trans.png)
[英]ConfigurationManager.AppSettings or only AppSettings?
[英]appSettings and ConfigurationManager.AppSettings issue
我搜索了网站,虽然我发现了一些非常有用的信息,但我无法弄清楚我的代码是怎么回事。 我有以下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文件的顶部。 我有一个非常强烈的怀疑,键盘后(即在我的大脑中)存在错误,但我无法解决这个问题。 有任何想法吗?
您是否尝试过使用WebConfigurationManager :
return System.Web.Configuration.WebConfigurationManager.AppSettings["APIKey"];
这是在Web应用程序中使用配置文件的首选选项 - 它处理嵌套配置文件等内容。
Visual Studio为MVC创建了2个web.config文件。 1位于根目录,另一位位于Views文件夹中。
你确定你使用的是正确的Web.Config文件吗? 您可能希望使用应用程序根目录中的那个,而不是Views目录中的那个。
检查以确保web.config文件的Build Action为“None”。 如果构建操作是“嵌入式资源”,我已经看到了这个问题。
您的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是什么样的?
我在我的解决方案中有两个项目我首先在类库项目中添加app.config文件,所有实例都是从控制台应用程序调用的,我在类lib项目的配置文件中添加了这些条目
<appSettings>
<add key="userName" value="user2" />
<add key="emilsLimit" value="50" />
</appSettings>
当我在类库项目中的类中获取这些时,它会抛出null异常但是当我从类库项目中删除app.config并在Console项目中添加它时它会工作。
注意:在控制台中添加了类lib项目引用
我敢打赌你在编写时使用正确的语法来访问它们: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>
你有没有尝试过:
return ConfigurationManager.AppSettings.Get("APIKey");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.