Skip to content

Instantly share code, notes, and snippets.

@songzheng45
Last active September 12, 2018 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save songzheng45/e04a12e2b51594923135ed6f850256e8 to your computer and use it in GitHub Desktop.
Save songzheng45/e04a12e2b51594923135ed6f850256e8 to your computer and use it in GitHub Desktop.
VS enable transforms configuration

利用 transform Configuration, 用来解决不同环境(如开发、生产环境)使用不同配置的情况, 只需切换DebugRelease或其它自定义配置, 最终生成相应的配置文件.

目录结构:

| App_Config
|   Web.Base.config
|   Web.Debug.config
|   Web.Release.config

编辑 projectname.csproj, 在末尾添加行:

<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="Web_config_AfterBuild" AfterTargets="AfterBuild" Condition="Exists('App_Config\Web.$(Configuration).config')">
  <TransformXml Source="App_Config\Web.Base.config" Destination="Web.config" Transform="App_Config\Web.$(Configuration).config" />
</Target>

网上普遍做法是不要将 Web.config 签入源码中, 基于 Web.Base.config 生成 Web.config, 因此对 Web.config 的所有修改都会被覆盖.

自定义的 XML 配置文件也可以创建 transform. 例如项目中有一个 extend.config 文件, 项目目录如下:

| App_Config
|   extend.Base.config
|   extend.Debug.config
|   extend.Release.config

编辑 projectname.csproj, 在末尾添加行:

<Target Name="extend_config_AfterBuild" AfterTargets="AfterBuild" Condition="Exists('App_Config\extend.$(Configuration).config')">
    <TransformXml Source="App_Config\extend.Base.config" Destination="extend.config" Transform="App_Config\extend.$(Configuration).config" />
</Target>

extend.Base.config 的内容如下:

<?xml version="1.0" encoding="utf-8"?>
<ExtendConfigs>
  <Items>
    <Item Key="coreservice.url" Value="http://127.0.0.1"/>
  </Items>
</ExtendConfigs>

extend.Debug.config 的内容如下:

<?xml version="1.0"?>
<ExtendConfigs xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <Items>
    <Item Key="coreservice.url" Value="http://192.168.1.100"
        xdt:Transform="Replace" xdt:Locator="Match(Key)"/>
  </Items>
</ExtendConfigs>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment