无需任何第三方扩展即可转换不同配置文件。






4.93/5 (10投票s)
针对不同环境的配置转换。
引言
本文档展示了如何自动化配置文件的转换过程,例如 App.config 和 Web.config 文件,当我们将应用程序部署到不同的目标环境(如开发、测试、生产)时。大多数应用程序在 App.config 或 Web.config 文件中都有需要在应用程序部署时不同的设置。自动化这些更改的过程可以避免每次部署都手动进行,从而减少繁琐和出错的可能性。
背景
在大多数实际场景中,我们用于开发的配置文件(app.config、web.config)与用于生产部署的配置文件不同。通常,我们希望将环境设置从开发环境更改为生产环境。从 .Net 4.0 开始,XDT 转换应运而生,可以执行这种类型的转换。
转换是如何工作的?
从 Visual Studio 创建一个名为“ConfigurationTransform”的控制台应用程序。
- 从解决方案配置菜单中单击“配置管理器”
- 从配置管理器单击“活动解决方案配置”下拉菜单,然后单击“新建”。
- 将配置名称设置为“Dev”,并选择“从以下复制设置”为“Release”,然后单击“确定”。
- 通过右键单击项目并单击“在文件资源管理器中打开文件夹”来打开项目目录
- 现在复制 App.config 文件并粘贴到同一目录中,然后将其重命名为 App.Dev.config。
- 通过右键单击项目并单击“卸载项目”来卸载项目。如果出现“保存更改”提示,请单击“是”。
- 右键单击项目,然后单击“编辑 ConfigurationTransform.csproj”
- 找到 Item group 'None Include="App.config"',并在其下方添加另一个代码块
<None Include="App.Dev.config"> <DependentUpon>App.config</DependentUpon> </None>
- 现在在 '</Project>' 标签之前添加此代码块。我们需要运行此 'Microsoft.Web.Publishing.Tasks.dll' MSbuild 任务来执行转换。
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" /> <Target Name="AfterCompile" Condition="Exists('App.$(Configuration).config')"> <!--Generate transformed app config in the intermediate directory--> <TransformXml Source="App.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="App.$(Configuration).config" /> <!--Force build process to use the transformed configuration file from now on.--> <ItemGroup> <AppConfigWithTargetPath Remove="App.config" /> <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config"> <TargetPath>$(TargetFileName).config</TargetPath> </AppConfigWithTargetPath> </ItemGroup> </Target>
- 现在通过右键单击项目并单击“重新加载项目”来重新加载项目
现在在 App.config 的配置部分中添加 appsettings 块,如下所示
<appSettings> <add key="adminEmail" value="admin@local.com" /> <add key="serviceUri" value="Local ServiceUri" /> </appSettings>
在 App.Dev.config 文件中添加 xml 命名空间属性 'xmlns:xdt',如下所示
<?xml version="1.0"?>
<!-- For more information on using app.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="adminEmail" value="admin@dev.com" xdt:Transform="Replace" xdt:Locator="Match(key)" />
<add key="serviceUri" value="Dev ServiceUri" xdt:Transform="Replace" xdt:Locator="Match(key)" />
</appSettings>
</configuration>
关注点
现在构建解决方案,转到 ../bin/Dev 文件夹,然后单击“ConfigurationTransform.exe”。它将打印转换后的配置值,如下所示
您可以为不同的环境(如 QA、测试、生产)添加更多配置。