如何连接到Web服务的web.config中编写的连接字符串
我们有一个名为“Service”的 Web 服务项目,在“service”的 web.config 中,我设置了连接字符串,如下所示:
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=L308;Initial Catalog=Dashboard;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
我尝试使用以下代码从另一个项目“DBConnector”访问连接字符串,但得到即使将“Service”的引用添加到“DBConnector”中,也会出现空引用异常。 使用 (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
We have a web service project called 'Service' and in the web.config of the 'service' I have set the connection string as follows:
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=L308;Initial Catalog=Dashboard;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I am trying to access the connection string from another project 'DBConnector' using the following code but getting null reference exception even though after adding the reference of the 'Service' into 'DBConnector'. using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要在 DBConnector 项目配置文件中包含连接字符串。添加对项目的引用不会在项目的主配置中引入该项目的配置
You will need to have the connection string in DBConnector project config file. Adding reference to a project doesn't bring in the config of that project in the main config of the project
如果我找到你了,
如果你想在你的库中使用服务的连接字符串,你就不能这样做。您需要将其公开为
service.cs 中的
属性或方法,或者
DBConnetor 添加为引用
如果 DBconnector 已添加为服务层中的引用,那么您可以通过您编写的代码轻松访问它
If i got you
You can not do that if you want to use the Connection string of service in you library. You need to expose that as property or method
in you service.cs
or
DBConnetor added as referance
If the DBconnector has added as referance in the Service layer than you can access it easily by the code you have written
如果您需要将该连接字符串设置为全局,以便所有应用程序和服务都可以使用它,您需要将其放入
machine.config
中。计算机配置位于
%WinDir%\Microsoft.NET\Framework\\CONFIG。
If you need want to make that connection string Global so all you applications and services can use it you will need to put it in the
machine.config
.The machine config if found here
%WinDir%\Microsoft.NET\Framework\\CONFIG.
似乎是不正确的做法。本来应该是相反的!
Seems to be incorrect thing to do. It should have been other-way around!