[ASP.NET]利用configSource將web.config的connectionStrings移到另一個config檔來維護

摘要:[ASP.NET]利用configSource將web.config的connectionStrings移到另一個config檔來維護

最近剛好看到這樣的寫法,把它記錄一下

connectionStrings:

一般web.config的connectionStrings會這樣設定

web.config

  <connectionStrings>
    <add name="MSSQL" connectionString="MSSQL" />
    <add name="Oralce" connectionString="Oracle" />
  </connectionStrings>

 也可以將connectionStrings移到另一個config檔來維護

web.config

<connectionStrings configSource="connections.config" />

connections.config

<?xml version="1.0" encoding="utf-8"?>
<connectionStrings>
  <add name="MSSQL" connectionString="MSSQL" />
  <add name="Oralce" connectionString="Oracle" />
</connectionStrings>

 appSettings:

appSettings也可以使用configSource將設定值移到另一個config檔來維護

web.config

<appSettings configSource="settings.config" />

settings.config

<?xml version="1.0" encoding="utf-8"?>
<appSettings>
  <add key="Blog" value="F6 Team" />
  <add key="Name" value="puma" />
  <add key="skill" value="ASP.NET" />
</appSettings>

也可以使用file來增加外部config檔的設定值

web.config

  <appSettings file="settings.config">
    <add key="Blog" value="F6 Team" />
    <add key="Name" value="puma" />
  </appSettings>

settings.config

<?xml version="1.0" encoding="utf-8"?>
<appSettings>
  <add key="skill" value="ASP.NET" />
</appSettings>

file與configSource的差別就是:

1.file:可以延伸外部檔案的setting
2.configSource:指定一個xxx.config(但web.cofing就不能設定了,不然會出錯)

以上每一種方式的執行結果都一樣,如下圖所示:

 

code:

using System;
using System.Web.Configuration;
using System.Configuration;

public partial class webconfig : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        foreach (string set in WebConfigurationManager.AppSettings)
        {
            Response.Write(string.Format("key:{0},value:{1}<br/>", set, WebConfigurationManager.AppSettings.Get(set)));
        }

        foreach (ConnectionStringSettings conn in WebConfigurationManager.ConnectionStrings)
        {
            Response.Write(string.Format("name:{0},connectionString:{1}<br/>", conn.Name, conn.ConnectionString));
        }
    }
}