![](/img/trans.png)
[英]How to encrypt Connectionstring written in web.config from codebehind?
[英]how access connectionstring in a web.config in other project from a WCF
我在從WCF“ Web服務”訪問web.config中的連接字符串時遇到一些困難
場景:Visual Studio 2010中的一個解決方案,其中包含2個Web項目,placement和wcfPlacement。 帶有連接功能的web.config位於放置項目中。
如圖所示,wcfPlacement沒有web.config,但是在構建時,它會生成一個。
從放置項目中,我可以使用ConfigurationManager.ConnectionStrings [“ XX”]。ConnectionString;訪問連接字符串。 - 好。
但是,如果我在該服務內部,則在嘗試訪問該服務時會給我一個錯誤,這迫使我在要數據庫訪問的每個類中聲明了一個連接字符串,這不好。
如何從wcf中訪問放置項目內web.config中的連接字符串?
我試過了:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["webV"].ConnectionString);
但它給我一個錯誤:System.NullReferenceException:對象引用未設置為對象的實例。 在wcfPlacement.Prospect.doLogin(字符串登錄,字符串senha)
在一個類中嘗試了這個:
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");
}
但我得到這個錯誤。 錯誤1類型或名稱空間名稱'配置'在名稱空間'System.Web'中不存在(您是否缺少程序集引用?)
您必須添加對System.Configuration命名空間的引用。
https://msdn.microsoft.com/zh-CN/library/system.configuration(v=vs.110).aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.