[ASP.Net]從 Web.config 檔案讀取連接字串

在ASP.Net與資料庫連結的時候,如果把連線字串寫在程式碼中,當連線失敗的時候網頁會出現程式碼哪幾行出錯,此時會將連線字串中的登入的帳號和密碼一併秀出,這樣被看光光時在非常的不好,所以才想到要直接去讀取Web.config裡面的連線字串。
這就是自學的壞處,常會使用錯誤的方法來撰寫,然後才能在錯誤中掙扎著長大...慘

參考網址:
 http://msdn.microsoft.com/zh-tw/library/ms178411%28v=vs.100%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

'讀取Web.config的連接字串
        Dim rootWebConfig As System.Configuration.Configuration
        rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/ASP_Test")  '填入檔案所屬的路徑
        Dim connString As System.Configuration.ConnectionStringSettings
        If (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0) Then
            connString = rootWebConfig.ConnectionStrings.ConnectionStrings("LocalEMSConnectionString")  '選擇要讀取的連線名稱
            If Not (connString.ConnectionString = Nothing) Then
                Console.WriteLine("Northwind connection string = {0}", connString.ConnectionString)
            Else
                Console.WriteLine("No Northwind connection string")
            End If
        End If


Web.Config內容
---------
<!--
  如需如何設定 ASP.NET 應用程式的詳細資訊,請造訪
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionstrings>
    <add connectionstring="Data Source=.;Initial Catalog=LocalEMS;User ID=Ryan;Password=123456789" name="LocalEMSConnectionString" providername="System.Data.SqlClient">
    <add connectionstring="Data Source=.;Initial Catalog=LocalEMS;User ID=Ryan;Password=123456789" name="LocalEMSConnectionString2" providername="System.Data.SqlClient">
  </add></add></connectionstrings>
  <system .web="">
    <compilation debug="true" explicit="true" strict="false" targetframework="4.0">
  </compilation></system>
    <system .webserver="">
        <defaultdocument>
            <files>
                <add value="Default.aspx">
            </add></files>
        </defaultdocument>
    </system>
</configuration>
---------



留言

這個網誌中的熱門文章

[Excel]將圖片放置於儲存格中

[電腦軟體]偵測遠端電腦的網路 Port是否開啟

[軟體]AUTOCAD關於開啟圖面時,字型找不到,而要手動指定成 chineset.shx 字型檔問題