Visual Studio C# 多环境配置 Web.config

开始以为像SpringBoot 那样,运行时也行效的,结果发现只对发布生效,不对运行时生效,也还行吧,凑活着用。

Visual Studio 为多环境配置 Web.config
不同的环境,存在不同的配置,如:数据库连接字符串,通过多配置,方便做环境切换,配置的修改

<!--最简单,最麻烦的做法--> <configuration>   <appSettings>      <!--正式-->     <!--<add key="DbConnection" value="Data Source=10.176.1.2;Initial Catalog=vipsoft;User ID=sa;Password=....;" />-->     <!--测试-->     <!--<add key="DbConnection" value="Data Source=172.16.0.1;Initial Catalog=vipsoft;User ID=sa;Password=123456;" />-->     <!--开发-->     <add key="DbConnection" value="Data Source=172.16.0.2;Initial Catalog=vipsoft;User ID=sa;Password=666666;" />    </appSettings> </configuration> 

好的做法。

添加解决方案配置

生成 -> 配置管理器
Visual Studio C# 多环境配置 Web.config
Visual Studio C# 多环境配置 Web.config
Visual Studio C# 多环境配置 Web.config
Visual Studio C# 多环境配置 Web.config

添加配置转换

右击 Web.config -> 添加配置转换
Visual Studio C# 多环境配置 Web.config
Visual Studio C# 多环境配置 Web.config

添加应对的配置

将不同环境的配置项,添加至对应的配置文件中
Web.config

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

Web.Test.config

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

属性值 xdt:Transform “SetAttributes” 指示此转换的目的是更改 Web.config 文件中现有元素的属性值。 xdt:Locator属性值“Match (键) ”指示要修改的元素是其key属性与此处指定的属性匹配的key元素。 元素的唯一其他属性 add 是 value,这就是部署 的Web.config 文件中将发生更改的内容。 此处显示的代码会导致 value 元素的属性 EnvironmentappSettings 在部署的 Web.config 文件中设置为“Test”。

  <system.web>     <compilation xdt:Transform="RemoveAttributes(debug)" />     <!--              在下例中,“Replace”转换将替换        web.config 文件的整个 <customErrors> 节。       请注意,由于        在 <system.web> 节点下仅有一个 customErrors 节,因此不需要使用“xdt:Locator”特性。              <customErrors defaultRedirect="GenericError.htm"         mode="RemoteOnly" xdt:Transform="Replace">         <error statusCode="500" redirect="InternalError.htm"/>       </customErrors>     -->   </system.web> 

xdt:Transform="RemoveAttributes(debug)" 属性指定要 debugsystem.web/compilation 已部署 的 Web.config 文件中的元素中删除该属性。 每次部署发布版本时,都会执行此操作。

Visual Studio C# 多环境配置 Web.config

预览转换

Visual Studio C# 多环境配置 Web.config

发布

修改发布配置
Visual Studio C# 多环境配置 Web.config
Visual Studio C# 多环境配置 Web.config

代码区分

#if TEST  #else  #endif 

Visual Studio C# 多环境配置 Web.config

发表评论

评论已关闭。

相关文章