如何根据正在运行的环境更改web.config中的连接字符串?

时间:2016-10-24 15:42:04

标签: iis web-config azure-devops web.config-transform

我正在使用visual studio团队服务,我使用他们的构建过程来构建代码并将代码推送到我们的开发服务器。问题是web.config有我的localhost连接字符串和dev服务器连接字符串注释掉了。如何设置web.config和构建过程以使用正确的连接字符串?

提前谢谢你!

2 个答案:

答案 0 :(得分:1)

您可以在VSTS中构建或发布期间通过Replace Token task替换文件中的特定值(例如web.config)。

例如:

enter image description here

对于Replace Token任务的这种配置,它可以将#{con}#替换为所有.config文件的con变量值(在构建定义的Variable选项卡中创建变量(变量名:con))(拥有#{ con(#code)在$(System.DefaultWorkingDirectory)位置。

<connectionStrings>
    <add name="DefaultConnection" connectionString="#{con}#" providerName="System.Data.SqlClient" />
  </connectionStrings>

答案 1 :(得分:-1)

web.config转换基于配置管理器中的Build进行此操作。

1)添加其他文件(web.config.debug,web.config.release)

2)在配置文件中添加标记

 <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings>
    <add name="MyConnectionString"
         connectionString="Data Source=MyServer;Initial Catalog=myDB;Integrated Security=True;"
         providerName="System.Data.SqlClient" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
  </connectionStrings>
</configuration>