从类库中读取web.config文件

4

我有两个项目: 1)类库,没有界面,只有API; 2)Web应用程序。

从Web应用程序中,我将调用类库API。

因此,在Web应用程序中,我拥有所有的web.config设置。但是当我调试它时,它总是返回null值。以下是代码片段:

 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>

有需要帮助的吗?
5个回答

11

你的语法不正确,应该是这样的

<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.ConnectionStrings["employeeDB"]将被读取。


谢谢您的纠正,但我的问题仍未得到解答,我应该在两个地方都放入该条目吗?(web.config 和 app.config) - Nick Kahn
@AbuHamzah:只有 ASP.NET 网站才需要 Web.config 文件。 - Icarus
+1 你是唯一一个指出 OP 应该使用 <connectionStrings> 的人。 - Icarus

2

刚看到这篇文章,我有同样的问题,但是我找到了解决方法..

在你的类库项目中添加System.Web.Configuration引用, 然后使用以下代码:

ConnectingString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

希望这能有所帮助。


WebConfigurationManager.ConnectionStrings["ConnectionString"] 这个对我有用,谢谢 @nilantha-ekanayake - Hardik Masalawala

1
此外,System.Configuration程序集不会自动添加到类库中。
  1. 在解决方案资源管理器中右键单击项目
  2. 点击“添加”>“引用”
  3. 在“程序集”>“框架”选项卡中勾选System.Configuration

0
您的标签有误,请使用'appSettings'而非'applicationSettings'。
<?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>

谢谢您的纠正,但我的问题仍未得到解答。我应该在两个地方都放入该条目吗?(web.config 和 app.config) - Nick Kahn
不需要,你只需要在 Web 应用程序的 web.config 文件中添加条目即可。 - Nitin Rastogi

0

appSettings 应该像这样

<appSettings>
    <add key="employeeDB" value="xxxx" />
</appSettings>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接