Read ConnectionString from web.config in ASP.NET 2.0

來源:互聯網
上載者:User
MSDN上How to: Read Connection Strings from the Web.config File的這篇文章用一個小demo示範了如何讀ConnectionString。
Demo Code: System.Configuration.Configuration rootWebConfig =System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
System.Configuration.ConnectionStringSettings connString;
if (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count)
{
    connString =rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
    if (null != connString)
     Console.WriteLine("Northwind connection string = \"{0}\"",connString.ConnectionString);
    else
        Console.WriteLine("No Northwind connection string");
}

我在wwwroot下有一個工程ProjectA,當去用的時候發現根本不能讀出自己的vcConnectionString,調試讀出的rootWebConfig.ConnectionStrings.ConnectionStrings.Count為1,而我的web.config中的確是只有一個name="vcConnectionString"的連接字串。開始懷疑如果讀不出我的來,那麼是不是與LocalSqlServer有關係了呢?使用rootWebConfig.ConnectionStrings.ConnectionStrings[0]讀出connString來發現果然是串連到aspnetdb的,connString.Name更是證實了這點。而我在web.config中根本沒有指定LocalSqlServer。檢查這段demo code,OpenWebConfiguration(null)導致了這個問題出現,提示了說如果使用null的話是In null, the root web.config file opened,這裡的root一定是wwwroot了。於是把null該為"~/"結果就正確了。可以讀出兩條ConnectionString了,一條是我定義的vcConnectionString,一條是machine.config裡定義的LocalSqlServer。
另外,預設情況下LocalSqlServer總是比自訂的connectionString優先。也就是說即使你先add了自己的,然後remove了LocalSqlServer後再add新的值,那麼rootWebConfig.ConnectionStrings.ConnectionStrings[0]讀出的還是LocalSqlServer的值
當然,簡單的方法還是有的:ConfigurationManager.ConnectionStrings["vcBlogConnectionString"].ConnectionString就可以完成任務了.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.