从 web.config 读取连接字符串 [英] To Read connection String from web.config

查看:42
本文介绍了从 web.config 读取连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IIS 上的 WCF 服务.我在从 web.config 文件读取连接字符串时遇到问题.我的连接字符串如下所示:

WCF service on IIS. I have got a problem with reading connection string from web.config file. my connection string looks like this :

    <connectionStrings>
  <add 
    name="ABC" 
    connectionString="DEF"
    providerName="GGG"
  />
</connectionStrings>

我在 Global.asax.cs 中的代码:

My code in Global.asax.cs :

protected void Application_Start(object sender, EventArgs e)
        {                    

           cons_Webdata =  WebConfigurationManager.ConnectionStrings["ABC"].ConnectionString;

        }

我在cons_Webdata = ......."中有错误消息:

I have error message in "cons_Webdata = ......." :

未将对象引用设置为对象的实例.

Object reference not set to an instance of an object.

怎么了?谢谢.

推荐答案

尝试使用 ConfigurationManager 而不是 WebConfigurationManager

Try using ConfigurationManager instead of 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");
        }

这篇关于从 web.config 读取连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆