web.config debug/releaseの内容を変換構文を使って切り替える

.Net FrameworkのWeb.Debug.config, Web.Release.configの内容を「変換構文」を使って、構成(Debug/Release)の切り替えによって変えることができたのでメモしておく。

 

Release構成でのビルドでは、Web.configに記載されている要素のうち、以下の3要素を変換構文を使って変更した。

  1. system.web
  2. connectionStrings
  3. appSettings

 

1. system.web

 compilation debug=trueの削除(Release時は、デバッグ情報は不要)

●Web.configの記述

<system.web>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
</system.web>

上記から、「debug="true"」を削除するには、RemoveAttributesを使う。


●Web.Release.config

<system.web>
    <!-- Disable Debug Mode -->
    <compilation xdt:Transform="RemoveAttributes(debug)" />
</system.web>


2. connectionStrings

 DBの接続情報を変更する。 (Debug/Release時は普通環境変わるだろう)

●Web.configの記述

<connectionStrings>
    <add name="ConnectionString"
        connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DB_TEST;Connect Timeout=60;Persist Security Info=True; User ID=sa;Password=manager"
            providerName="System.Data.SqlClient" />
</connectionStrings>

「connectionString」の情報をがっさり入れ替える。


●Web.Release.configの記述

<connectionStrings>
    <add name="ConnectionString"
      connectionString="Data Source=127.0.0.1\SQLEXPRESS;Initial Catalog=RELEASE_DB;;Connect Timeout=60;Persist Security Info=False; User ID=hoge;Password=1234"
      xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>

xdt:Locator="Match(name)"→name要素が「connectionString」に一致すれば

xdt:Transform="SetAttributes"→記載している属性を内容ごと全て入れ替える。


3. appSettings

 環境情報を変更する。 (Debug/Release時は普通環境情報も変わるだろう)


●Web.configの記述

これも2と同じ。

<appSettings>
    <add key="Environment" value="Dev" />
</appSettings>


●Web.Release.configの記述

<appSettings>
    <add key="Environment" value="PRODUCTION" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
</appSettings>



VisualStudioを使って変換の確認

ソリューションエクスプローラーでWeb.Release.configファイルにフォーカスし、右クリックで「プレビューおよび変換」を選択する。




















変換プレビュー

こんな感じで変換される。














※おまけ

ちなみに、appSettingsの"Environment"を取得する方法は以下の通り。

string env = ConfigurationManager.AppSettings["Environment"];
logger.Trace("trace log message: env->{0}", env);


(参考)

→各属性の構文詳細が記載されている。
→基本的な使い方が記載されている。


コメント

このブログの人気の投稿

ソリューション構成ごとにconfigファイルを作成する

C++の古いプロジェクトのビルドでerror MIDL2311 : statements outside library block are illegal in mktyplib compatability mode