可以对所有连接字符串输入使用app键,并在连接字符串上读取它们,如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" />
答案 0 :(得分:3)
正如@ErtürkÖztürk已经说过 - 这是不可能的。
如果您搜索更多或更少的干净方式,我建议您使用SqlConnectionStringBuilder
或DbConnectionStringBuilder
如果您不使用MSSQL数据库。
在您的代码中,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;
答案 1 :(得分:1)
It's not possible。实际上你不需要这样做,这就是为什么它不可能。因为您可以像AppSettings一样更改web.config的其他部分。
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString =
String.Format("Data Source={0};Initial Catalog={1};UserID={2};Password={3}",
"server", "db", "ID", "Pass");