Wella
Wella

Reputation: 1476

How to read App Setting key in Web config Connection string?

It is possible to use app keys for all the connection string inputs and read those on connection string like bellow

<add name="DefaultConnection" connectionString="Data Source=$(Server);Initial Catalog=$(Catalog);User ID=$(User);Password=$(Password)" providerName="System.Data.SqlClient" />



<add key="$(Server)" value="xxxx" />
<add key="$(Catalog)" value="xxxx" />
<add key="$(User)" value="xxxx" />
<add key="$(Password)" value="xxxx" />

Upvotes: 0

Views: 1040

Answers (2)

teo van kot
teo van kot

Reputation: 12491

As @Ertürk Öztürk already say - it's not possible.

If you searching for more or less clean way to do it i suggest you to use SqlConnectionStringBuilder or DbConnectionStringBuilder if you using not MSSQL data base.

In your code it will be like this with SqlConnectionStringBuilder:

//create connection string builder
System.Data.SqlClient.SqlConnectionStringBuilder connectionStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();

//set all properties from your WebConfig
connectionStringBuilder.DataSource = ConfigurationManager.AppSettings["Server"];
connectionStringBuilder.InitialCatalog = ConfigurationManager.AppSettings["Catalog"];
connectionStringBuilder.UserID = ConfigurationManager.AppSettings["User"];
connectionStringBuilder.Password = ConfigurationManager.AppSettings["Password"];

//not you can get rigth formatted connection string
var connectionString = connectionStringBuilder.ConnectionString;

Upvotes: 3

ErTR
ErTR

Reputation: 905

It's not possible. Actually you don't need to do this, that's why it's not possible. Because you can change the other parts of web.config same like AppSettings.

ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString =
String.Format("Data Source={0};Initial Catalog={1};UserID={2};Password={3}",
 "server", "db", "ID", "Pass");

Upvotes: 1

Related Questions