首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 2.0 連接字串管理最佳實踐:web.config 宣告式語法與程式碼讀取雙軌並行

     編輯:關於ASP.NET

ASP.NET 2.0 引入 <connectionStrings> 組態區段與宣告式運算式語法,讓連接字串集中管理、零硬編碼成為可能。

Web.config 宣告式設定

<connectionStrings>
  <add name="Pubs" 
       connectionString="Server=localhost;Integrated Security=True;Database=pubs;Persist Security Info=True" 
       providerName="System.Data.SqlClient" />
  <add name="Northwind" 
       connectionString="Server=localhost;Integrated Security=True;Database=Northwind;Persist Security Info=True" 
       providerName="System.Data.SqlClient" />
</connectionStrings>

宣告式運算式語法(.aspx/控制項標記中使用)

  • ConnectionString="<%$ ConnectionStrings:Pubs %>"
  • ProviderName="<%$ ConnectionStrings:Pubs.ProviderName %>"

執行時由 ASP.NET 剖析器解析,SqlDataSource 等資料來源控制項直接支援。

程式碼中讀取

using System.Web.Configuration;

// 讀取連接字串
string connStr = ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
// 或
string connStr = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;

優勢總結

  1. 集中管理:單一位置維護所有連接字串
  2. 型別安全:providerName 明確指定 ADO.NET 提供者
  3. 部署彈性:開發/測試/正式環境僅修改 config,程式碼零變動
  4. 安全性:可搭配 configProtectionProvider 加密敏感資訊
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved