I kno" /> I kno" /> I kno"/>

ASP.NET and Visual Studio 2019: how to set up Web.Debug and Web.Release if you have configSource in Web.config?

1.3k Views Asked by At

In my ASP.NET web form, this is what my connection string looks like in my Web.config file:

<connectionStrings configSource="MySecrets.config"/>

I know that I can use Web.Debug and Web.Release to change the connection strings so that they are not exposed when the web app is released.

However, the examples provided by Visual Studio mention:

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>

However, this references a <connectionStrings> section in the Web.config file that I don't have in the first place, because in my project I have:

<connectionStrings configSource="MySecrets.config"

How can I set up the Web.Release to replace the MySecrets.config file so that it's not visible once published?

1

There are 1 best solutions below

3
Josue Barrios On BEST ANSWER

use the preprocessor to switch between connectionstring, for this you should have both connectionstrings.

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>

code behind

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
}

reference: #if (C# Reference)