IIS上的WCF服务。 我从web.config文件中读取连接字符串时遇到问题。 我的连接字符串如下所示:
<connectionStrings>
<add
name="ABC"
connectionString="DEF"
providerName="GGG"
/>
</connectionStrings>
我在Global.asax.cs中的代码:
protected void Application_Start(object sender, EventArgs e)
{
cons_Webdata = WebConfigurationManager.ConnectionStrings["ABC"].ConnectionString;
}
我在“cons_Webdata = .......”中有错误消息:
对象引用未设置为对象的实例。
怎么了? 感谢。
答案 0 :(得分:3)
尝试使用ConfigurationManager而不是WebConfigurationManager
protected void Application_Start(object sender, EventArgs e)
{
cons_Webdata = ConfigurationManager.ConnectionStrings["ABC"].ConnectionString;
}
否则,请使用http://msdn.microsoft.com/en-us/library/ms178411.aspx
中的代码示例 System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
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 :(得分:1)
查看如何在Web应用程序here中使用WebConfigurationManager。您需要从配置文件中读取连接字符串部分,然后使用它们,如下所示:
// Get the connectionStrings section.
ConnectionStringsSection connectionStringsSection =
WebConfigurationManager.GetSection("connectionStrings")
as ConnectionStringsSection;
// Get the connectionStrings key,value pairs collection.
ConnectionStringSettingsCollection connectionStrings =
connectionStringsSection.ConnectionStrings;
// Get the collection enumerator.
IEnumerator connectionStringsEnum =
connectionStrings.GetEnumerator();
// Loop through the collection and
// display the connectionStrings key, value pairs.
int i = 0;
Console.WriteLine("[Display the connectionStrings]");
while (connectionStringsEnum.MoveNext())
{
string name = connectionStrings[i].Name;
Console.WriteLine("Name: {0} Value: {1}",
name, connectionStrings[name]);
i += 1;
}