需求:在開發asp.net應用程序時,往往想在debug和release環境下使用不同的配置,而web.config文件卻只有一個
解決方案:可以在原來的web.config中寫下debug環境下的配置,然后在web.release.config中寫下release環境下特有的配置。常見情況寫法舉例如下:
1.替換某節點的某屬性值,使用“SetAttributes”轉換將更改 “connectionString”的值,僅在“Match”定位器查找到屬性為“name”的值為“MyDB”時使用此節點的“connectionString”的值。其他不用改變的屬性值無需填寫。
<connectionStrings> <add name="MyDB" connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/> </connectionStrings>
2.替換整個節點,“Replace”轉換將替換web.config 文件的整個 <customErrors> 節。 請注意,由於在 <system.web> 節點下僅有一個 customErrors 節,因此不需要使用“xdt:Locator”特性。
<customErrors defaultRedirect="GenericError.htm" mode="RemoteOnly" xdt:Transform="Replace"> <error statusCode="500" redirect="InternalError.htm"/> </customErrors>
3.刪除某個節點的某個屬性,使用RemoveAttributes。刪除compilation節點的debug這個屬性。
<compilation xdt:Transform="RemoveAttributes(debug)" />
以上經過測試可用。
總結:通過在web.release.config或web.debug.config中按指定的格式查找和替換節點內容,可以實現web.config按生成環境的不同生成不同的版本,方便調試和發布。