我阅读了许多与配置管理器相关的主题,但无法解决问题。我只想阅读连接字符串以及Web应用程序中CLASS LIBRARY的一些appsetting键。
我引用了System.Configuration Class。
这是我的代码
using System.Configuration;
...
string constr = ConfigurationManager.ConnectionStrings["cbuddydb"].ConnectionString;
string strUserName = ConfigurationManager.AppSettings["username"];
string strPwd = ConfigurationManager.AppSettings["password"];
但它似乎从不同的配置文件中读取。不是来自我项目中的web.config。因为读取的值是错误的
请帮助使用正确的代码 编辑:下面的web.config
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.data>
<connectionStrings>
<clear />
<add name="cbuddydb" connectionstring=
"Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=myDataBase;Persist Security Info=True;
User=@username;Password=@password;Option=3" providerName="MySql.Data.MySqlClient" password=""/>
</connectionStrings>
<appSettings >
<clear />
<add key="username" value ="6/0RUNnSmUBsbdNoCg+9Sw=="/>
<add key="password" value =""/>
</appSettings>
</system.data>
</configuration>
答案 0 :(得分:4)
原因是配置文件继承。索引0处的连接字符串可能不在您的配置文件中,但它可能已从machine.config等继承。查看ASP.Net配置文件层次结构和继承:http://msdn.microsoft.com/en-us/library/ms178685.aspx
您可以通过在web.config中指定以下内容来清除继承的连接字符串
<connectionStrings>
<clear />
<add name=”MyConnString” connectionString=“Whatever“ />
</connectionStrings>
编辑:在您的配置中,将connectionStrings和appSettings标记直接放在配置元素下方。它们不应该在system.data元素中。它们是配置元素的直接子元素。并删除providerName之后的额外密码属性。我无法验证您的连接字符串,因为我不知道您是如何使用它的。
<configuration>
<connectionStrings>
<clear />
<add name="cbuddydb" connectionString=
"Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=myDataBase;Persist Security Info=True;
User=@username;Password=@password;Option=3" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
<appSettings >
<add key="username" value ="6/0RUNnSmUBsbdNoCg+9Sw=="/>
<add key="password" value =""/>
</appSettings>
<system.data>
....
您应该考虑加密配置文件中的敏感信息,例如密码。