[英]how access connectionstring in a web.config in other project from a WCF
I'm having some difficulty to access the connectionstrings in web.config from a WCF "web services" 我在从WCF“ Web服务”访问web.config中的连接字符串时遇到一些困难
cenario: a solution inside visual studio 2010 with 2 web projects, placement and wcfPlacement. 场景:Visual Studio 2010中的一个解决方案,其中包含2个Web项目,placement和wcfPlacement。 the web.config that has the connectionstings are inside the placement project.
带有连接功能的web.config位于放置项目中。
The wcfPlacement does not have a web.config as you can see in the picture, but when I build it, it generates one. 如图所示,wcfPlacement没有web.config,但是在构建时,它会生成一个。
from the placement project I can access the connection strings using ConfigurationManager.ConnectionStrings["XX"].ConnectionString; 从放置项目中,我可以使用ConfigurationManager.ConnectionStrings [“ XX”]。ConnectionString;访问连接字符串。 - ok.
- 好。
but if I'm inside the service, it gives me an error when I try to access, forcing me to have a connection string declared inside each class that I want database access, and that's not good. 但是,如果我在该服务内部,则在尝试访问该服务时会给我一个错误,这迫使我在要数据库访问的每个类中声明了一个连接字符串,这不好。
How can I access the connectionstrings that are in th web.config inside the placement project from the wcf ? 如何从wcf中访问放置项目内web.config中的连接字符串?
I tried: 我试过了:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["webV"].ConnectionString);
but it gives me an error: System.NullReferenceException: Object reference not set to an instance of an object. 但它给我一个错误:System.NullReferenceException:对象引用未设置为对象的实例。 at wcfPlacement.Prospect.doLogin(String login, String senha)
在wcfPlacement.Prospect.doLogin(字符串登录,字符串senha)
tried this inside a class: 在一个类中尝试了这个:
System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/placement");
System.Configuration.ConnectionStringSettings connString;
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString =
rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
if (connString != null)
Console.WriteLine("Northwind connection string = \"{0}\"",
connString.ConnectionString);
else
Console.WriteLine("No Northwind connection string");
}
but I get this error. 但我得到这个错误。 Error 1 The type or namespace name 'Configuration' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)
错误1类型或名称空间名称'配置'在名称空间'System.Web'中不存在(您是否缺少程序集引用?)
You have to add reference to System.Configuration namespace. 您必须添加对System.Configuration命名空间的引用。
https://msdn.microsoft.com/en-us/library/system.configuration(v=vs.110).aspx https://msdn.microsoft.com/zh-CN/library/system.configuration(v=vs.110).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.