2

在我的 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>

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

<connectionStrings configSource="MySecrets.config"

如何设置 Web.Release 以替换MySecrets.config文件,使其在发布后不可见?

4

1 回答 1

2

使用预处理器在连接字符串之间切换,为此您应该同时拥有两个连接字符串。

网络配置

<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# 参考)

于 2019-11-20T17:28:42.907 回答