如何使用Web.config转换区分Debug与Production环境的连接字符串?请提供实现示例
如何使用Web.config转换区分Debug与Production环境的连接字符串?请提供实现示例
没问题!我来给你一步步演示怎么用Web.config转换实现Debug和Production环境的连接字符串区分,这是ASP.NET项目里非常常用的配置技巧~
核心思路
ASP.NET项目默认会生成Web.Debug.config和Web.Release.config(Production环境一般对应Release配置)两个转换文件,它们会在编译/发布时自动替换主Web.config里的对应内容,实现不同环境的配置隔离。
步骤1:配置主Web.config(Production环境)
首先把Production环境的连接字符串放到主Web.config的connectionStrings节点里,这是默认的生产环境配置:
<configuration> <!-- 其他配置节点 --> <connectionStrings> <add name="SomethingEntities" connectionString="metadata=res://*/DataModel.SomethingEntity.csdl|res://*/DataModel.SomethingEntity.ssdl|res://*/DataModel.SomethingEntity.msl;provider=System.Data.SqlClient;provider connection string="data source=server;initial catalog=Something;persist security info=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient"/> </connectionStrings> </configuration>
步骤2:配置Web.Debug.config(Debug环境)
打开项目里的Web.Debug.config,添加以下转换代码,实现Debug环境下替换为你的开发连接字符串:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <connectionStrings> <!-- 定位到主Web.config里name为SomethingEntities的节点,然后完全替换成开发环境的配置 --> <add name="Something_Dev_Entities" connectionString="metadata=res://*/DataModel.Something_Dev_Entity.csdl|res://*/DataModel.Something_Dev_Entity.ssdl|res://*/DataModel.Something_Dev_Entity.msl;provider=System.Data.SqlClient;provider connection string="data source=server;initial catalog=Something_Dev;persist security info=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" xdt:Transform="Replace" xdt:Locator="Match(name)" name="SomethingEntities" /> </connectionStrings> </configuration>
这里的关键属性说明:
xdt:Locator="Match(name)":告诉转换引擎,找到主Web.config里name属性为SomethingEntities的那个<add>节点xdt:Transform="Replace":用当前这个新的节点完全替换找到的原节点,这样Debug环境下就会自动切换成开发版的连接字符串和名称
步骤3:验证效果
- 在Visual Studio的顶部配置下拉框里选择Debug,然后运行项目,此时程序会使用Web.Debug.config转换后的开发连接字符串
- 选择Release(对应Production环境)运行或发布项目,则会使用主Web.config里的生产环境配置
备注:内容来源于stack exchange,提问作者Doug Gardiner
相关产品推荐
相关产品推荐

