ASP.NET和Visual Studio 2019:如果Web.config中有configSource,如何设置Web.Debug和Web.Release?

问题描述 投票:1回答:1

在我的ASP.NET Web表单中,这是我的连接字符串在Web.config文件中的样子:

<connectionStrings configSource="MySecrets.config"/>

[我知道我可以使用Web.Debug和Web.Release更改连接字符串,以便在发布Web应用程序时不显示它们。

但是,Visual Studio提供的示例提到:

In the example below, the "SetAttributes" transform will change the value of 
"connectionString" to use "ReleaseSQLServer" only when the "Match" locator 
finds an attribute "name" that has a value of "MyDB".

<connectionStrings>
  <add name="MyDB" 
    connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" 
    xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>

但是,这引用了我最初没有的Web.config文件中的<connectionStrings>部分,因为在我的项目中我拥有:

<connectionStrings configSource="MySecrets.config"

我如何设置Web.Release以替换MySecrets.config文件,以便一旦发布就不可见?

c# asp.net web-config visual-studio-2019 xdt-transform
1个回答
0
投票
使用预处理器在连接字符串之间切换,为此您应该同时拥有两个连接字符串。

web.config

<connectionStrings> <add name="Project.Properties.Settings.ConnString_A" connectionString="" providerName="System.Data.SqlClient" /> <add name="Project.Properties.Settings.ConnString_B" connectionString="" providerName="System.Data.SqlClient" /> </connectionStrings>

后面的代码

public SqlConnection conn { get; set; } public DbContext() { #if DEBUG conn = new SqlConnection(Properties.Settings.Default.ConnString_A); #else conn = new SqlConnection(Properties.Settings.Default.ConnString_B); #endif }

参考:#if (C# Reference)
© www.soinside.com 2019 - 2024. All rights reserved.