Asp.net 从类库读取web.config
我有两个项目 1) 类库没有接口,只有一个api 2) web应用程序 从web应用程序中,我将调用类库api 因此,我在web应用程序中有所有的web.config设置,但当我调试时,它总是返回null值,下面是代码snippit:Asp.net 从类库读取web.config,asp.net,web-config,app-config,Asp.net,Web Config,App Config,我有两个项目 1) 类库没有接口,只有一个api 2) web应用程序 从web应用程序中,我将调用类库api 因此,我在web应用程序中有所有的web.config设置,但当我调试时,它总是返回null值,下面是代码snippit: public static string readingDB { get { string result = null; result
public static string readingDB
{
get
{
string result = null;
result = ConfigurationManager.AppSettings["employeeDB"]; //conn string
if (!string.IsNullOrEmpty(result))
{
return result;
}
else
{
return ""; //???? THROW EXCEPTION???
}
}
}
我也尝试过,在类库项目中创建一个新的app.config,在那里有相同的appsettings,但不起作用
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<applicationSettings>
<add name="employeeDB" connectionString="Data Source=servername;Initial Catalog=employee;Persist Security Info=True;User ID=userid;Password=password;"/>
</applicationSettings>
<customErrors mode="On"/>
</configuration>
有什么帮助吗?您的标记错误。它应该是“应用程序设置”而不是“应用程序设置”
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add name="employeeDB" connectionString="Data Source=servername;Initial Catalog=employee;Persist Security Info=True;User ID=userid;Password=password;"/>
</appSettings>
<customErrors mode="On"/>
</configuration>
您的语法不正确,应该是
<configuration>
<appSettings>
<add key="employeeDB" value="Data Source=servername;Initial Catalog=employee;Persist Security Info=True;User ID=userid;Password=password;"/>
</appSettings>
</configuration>
或者更准确地说,因为它是一个连接字符串
<configuration>
<connectionStrings>
<add name="employeeDB" connectionString="Data Source=servername;Initial Catalog=employee;Persist Security Info=True;User ID=userid;Password=password;"/>
</connectionStrings>
</configuration>
这将由ConfigurationManager读取。ConnectionString[“employeeDB”]应用程序设置应如下所示
<appSettings>
<add key="employeeDB" value="xxxx" />
</appSettings>
刚看到帖子,我也遇到了同样的问题,但我找到了解决办法。。 将
System.Web.Configuration
引用添加到类库prj
然后
ConnectingString=WebConfigurationManager.ConnectionStrings[“ConnectionString”].ConnectionString代码>
希望这将有助于此外,系统配置程序集不会自动添加到类库中
右键单击解决方案资源管理器中的项目
单击添加>引用
在程序集>框架选项卡中检查System.Configuration
谢谢你的正确回答,但是我的问题仍然没有得到回答。我应该把这两个地方都记下来吗?(web.config和app.config)@AbuHamzah:你应该只为ASP.NET网站设置web.config。+1你是唯一一个真正指出OP应该使用
的人。谢谢你的更正,但我的问题仍然没有得到回答。我是否应该同时设置两个条目?(web.config和app.config)不,您只需要web应用程序的web.config中的条目。WebConfigurationManager.ConnectionStrings[“ConnectionString”]
这对我有用,谢谢@nilantha ekanayake