App.config使用ASP.NET Web Project的Transformation模式编译方式

我们在项目开发的时候,经常会在不同的环境中使用不同的配置文件,那么编译时是否可以根据编译模式自动生成配置文件呢?我们来试试看:

1、创建对应configuration的App.config文件,比如:App.Debug.config、App.Release.config。

2、编辑项目文件,将App.*.config文件的Build Action修改为Content,参考如下:

复制代码
<Content Include="App.config" />
    <Content Include="App.Debug.config">
      <DependentUpon>App.config</DependentUpon>
    </Content>
    <Content Include="App.Publish.config">
      <DependentUpon>App.config</DependentUpon>
    </Content>
    <Content Include="App.Release.config">
      <DependentUpon>App.config</DependentUpon>
    </Content>
复制代码

3、在</Project>标签前加入以下配置:

复制代码
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)MicrosoftVisualStudiov10.0WebMicrosoft.Web.Publishing.Tasks.dll" />
  <Target Name="AfterCompile" Condition="exists('app.$(Configuration).config')">
    <TransformXml Source="app.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="app.$(Configuration).config" />
    <ItemGroup>
      <AppConfigWithTargetPath Remove="app.config" />
      <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
        <TargetPath>$(TargetFileName).config</TargetPath>
      </AppConfigWithTargetPath>
    </ItemGroup>
  </Target>
复制代码

重新加载项目,就可以看到App.config和Web.config相同的效果。

如果不想使用各种xdt语法,可以直接指定configuration的App.config:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
  <AppConfig>App.Release.config</AppConfig>
</PropertyGroup>

使用上下文变量修改为更通用的配置:

<PropertyGroup>
  <AppConfig>App.$(Configuration).config</AppConfig>
</PropertyGroup>

出处:https://www.cnblogs.com/junchu25/p/3891810.html

您的资助是我最大的动力!
金额随意,欢迎来赏!
款后有任何问题请给我留言。

如果,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的推荐按钮。
如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的关注我。(●'◡'●)

如果你觉得本篇文章对你有所帮助,请给予我更多的鼓励,求打             付款后有任何问题请给我留言!!!

因为,我的写作热情也离不开您的肯定支持,感谢您的阅读,我是【Jack_孟】!

原文地址:https://www.cnblogs.com/mq0036/p/15396344.html