Web.config をプロジェクトの発行時に切り替える - ASP.NET

Web.Config をプロジェクト(アプリケーション)の発行時に切り替える手順を紹介します。

概要

アプリケーションを本番環境にリリースする際にリリース用のWeb.configに切り替えたい場合があります。
リリース時に手で変更するのは手間がかかるため、あらかじめ設定した値にWeb.configを変換することでリリース用のWeb.configに切り替える方法を紹介します。
補足
Webアプリケーションの発行時に切り替える方法のため、Visual Studioでデバッグする場合などではWeb.configの変更は反映されませんので注意してください。

Web.config ファイルとデフォルトの動作の確認

ASP.NET Webアプリケーションのプロジェクトを作成します。


ソリューションエクスプローラーでWeb.config のファイルのノードをダブルクリックして展開します。
子ノードに[Web.Debug.config]と[Web.Release.config]の項目が表示されます。


コード (Web.config)

デフォルトのWeb.configのコードは下記です。
Web.config
<?xml version="1.0" encoding="utf-8"?>

<!--
  ASP.NET アプリケーションの構成方法の詳細については、
  https://go.microsoft.com/fwlink/?LinkId=169433 を参照してください
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.8"/>
    <httpRuntime targetFramework="4.8"/>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>

</configuration>
Web.Debug.config
<?xml version="1.0" encoding="utf-8"?>

<!-- web.config 変換の使用方法の詳細については、https://go.microsoft.com/fwlink/?LinkId=125889 を参照してください -->

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <!--
    次の例では、"MyDB" という値を持つ "name" 属性が "Match" ロケーターで
    見つかった場合にのみ、"SetAttributes" 変換によって "connectionString" の
    値が "ReleaseSQLServer" を使用するように変更されます。
    
    <connectionStrings>
      <add name="MyDB" 
        connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" 
        xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
    </connectionStrings>
  -->
  <system.web>
    <!--
      
      次の例では、web.config ファイルの <customErrors> セクション全体が 
      "Replace" 変換によって置き換えられます。
      <system.web> ノードには customErrors セクションが 1 つしかないため、
      "xdt:Locator" 属性を使用する必要はありません。
      
      <customErrors defaultRedirect="GenericError.htm"
        mode="RemoteOnly" xdt:Transform="Replace">
        <error statusCode="500" redirect="InternalError.htm"/>
      </customErrors>
    >
    -->
  </system.web>
</configuration>
Web.Release.config
<?xml version="1.0" encoding="utf-8"?>

<!-- web.config 変換の使用方法の詳細については、https://go.microsoft.com/fwlink/?LinkId=125889 を参照してください -->

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <!--
    次の例では、"MyDB" という値を持つ "name" 属性が "Match" ロケーターで
    見つかった場合にのみ、"SetAttributes" 変換によって "connectionString" の
    値が "ReleaseSQLServer" を使用するように変更されます。
    
    <connectionStrings>
      <add name="MyDB" 
        connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" 
        xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
    </connectionStrings>
  -->
  <system.web>
    <compilation xdt:Transform="RemoveAttributes(debug)" />
    <!--
      
      次の例では、web.config ファイルの <customErrors> セクション全体が 
      "Replace" 変換によって置き換えられます。
      <system.web> ノードには customErrors セクションが 1 つしかないため、
      "xdt:Locator" 属性を使用する必要はありません。
      
      <customErrors defaultRedirect="GenericError.htm"
        mode="RemoteOnly" xdt:Transform="Replace">
        <error statusCode="500" redirect="InternalError.htm"/>
      </customErrors>
    -->
  </system.web>
</configuration>

プログラム

Web.ConfigにappSettings タグ add タグを記述します。
Weo.config
<?xml version="1.0" encoding="utf-8"?>

<!--
  ASP.NET アプリケーションの構成方法の詳細については、
  https://go.microsoft.com/fwlink/?LinkId=169433 を参照してください
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.8"/>
    <httpRuntime targetFramework="4.8"/>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
	<appSettings>
		<add key="AppInfo" value="初期値です。"/>
	</appSettings>
</configuration>

Webフォームを作成し、下記のコードを記述します。
DisplayInfo.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DisplayInfo.aspx.cs" Inherits="WebConfigDemo.DisplayInfo" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </div>
    </form>
</body>
</html>
DisplayInfo.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;

namespace WebConfigDemo
{
  public partial class DisplayInfo : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      string value = ConfigurationManager.AppSettings["AppInfo"];
      Label1.Text = value;
    }
  }
}

解説

ConfigurationManager.AppSettings を利用してWeb.configファイルから値を取得して、Label1に表示します。
詳しい動作はこちらの記事を参照してください。

実行結果

プロジェクトを実行します。Webブラウザが開きますので、DisplayInfo.aspx を開きます。
下図の画面が表示されます。

プログラム : Web.Debug.config, Web.Release.config を利用する

先のプログラムのWeb.Debug.config, Web.Release.config を下記に変更します。
Web.Debug.config
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.web>
  </system.web>
  <appSettings>
    <add key="AppInfo" value="デバッグ版の値です。" xdt:Locator="Match(key)" xdt:Transform="Replace"/>
  </appSettings>
</configuration>
Web.Release.config
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.web>
    <compilation xdt:Transform="RemoveAttributes(debug)" />
  </system.web>
  <appSettings>
    <add key="AppInfo" value="リリース版の値です。" xdt:Locator="Match(key)" xdt:Transform="Replace"/>
  </appSettings>
</configuration>

解説

下記のコードでWeb.configに変更をしています。
xdt:Locator="Match(key)" により、Web.config の 同じ位置のタグで key属性の値が一致するタグに対して処理を実行します。 xdt:Transform="Replace" により、タグの値の置換を実行します。
    <add key="AppInfo" value="デバッグ版の値です。" xdt:Locator="Match(key)" xdt:Transform="Replace"/>

動作の確認

ソリューションエクスプローラーでプロジェクトのノードをクリックして選択し右クリックします。 下図のポップアップメニューが表示されますので、[発行]の項目をクリックします。


プロジェクトの発行画面が表示されます。


[構成]を"Release" の設定でアプリケーションを発行します。


出力先のフォルダにファイル一式が出力されます。


Web.config のファイルを確認します。下記の内容になっています。Web.Relase.config に記述した値が反映されていることが確認できます。
Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
  ASP.NET アプリケーションの構成方法の詳細については、
  https://go.microsoft.com/fwlink/?LinkId=169433 を参照してください
  -->
<configuration>
  <system.web>
    <compilation targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <appSettings>
    <add key="AppInfo" value="リリース版の値です。" />
  </appSettings>
</configuration>
<!--ProjectGuid: FF9EA0A9-EA3B-4DAD-B5D8-454F8C091AF8-->

Webサーバーに配置して実行すると下図の実行結果になります。


アプリケーションの発行画面で[構成]を"Debug"にしてアプリケーションを発行します。


Debugで発行した場合は、Web.configが下記になります。Web.Debug.config に記述した値が反映されていることが確認できます。
Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
  ASP.NET アプリケーションの構成方法の詳細については、
  https://go.microsoft.com/fwlink/?LinkId=169433 を参照してください
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <appSettings>
    <add key="AppInfo" value="デバッグ版の値です。" />
  </appSettings>
</configuration>
<!--ProjectGuid: FF9EA0A9-EA3B-4DAD-B5D8-454F8C091AF8-->
注意
Web.Release.config や Web.Debug.config が Web.config に反映されるのはアプリケーションを発行した場合のみです。Visual Studioでデバッグ実行した場合は、 Web.*.config の内容は反映されないため注意が必要です。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2023-08-28
作成日: 2021-01-02
iPentec all rights reserverd.