出頭喜歡:由於請求參數,我可以更改web.config連接字符串嗎?
if(Request["connectionToUse"] + "" == "constr1")
// use a connection string 1
else
// use a connection string 2
是有可能的.NET?
出頭喜歡:由於請求參數,我可以更改web.config連接字符串嗎?
if(Request["connectionToUse"] + "" == "constr1")
// use a connection string 1
else
// use a connection string 2
是有可能的.NET?
編輯:這可能是一個非常糟糕的主意,因爲由俄德說,但如果你真的想那麼:
修改基於請求參數看下面的例子中,webconfig:
string strDevConnection = @"Data Source=DEVELOPMENT\SQLEXPRESS;Initial Catalog=sqlDB;Persist Security Info=True;User ID= ;Password= ";
string strLiveConnection = @"Data Source=PRODUCTION\SQLEXPRESS;Initial Catalog=sqlDB;User id= ;password= ";
Configuration myWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
if (Request["connectionToUse"] + "" == "constr1")
{
myWebConfig.ConnectionStrings.ConnectionStrings["constr1"].ConnectionString = strDevConnection; //constr1 is the name of the current connectionstring in the web.config
}
else
{
myWebConfig.ConnectionStrings.ConnectionStrings["constr2"].ConnectionString = strLiveConnection;
}
myWebConfig.Save(); //Save the changes to web config
有你web.config
兩個連接字符串,只需簡單地引用一個你想使用:
<connectionStrings>
<add
name="conn1" connectionString="..."
providerName="System.Data.SqlClient"
/>
<add
name="conn2" connectionString="..."
providerName="System.Data.SqlClient"
/>
</connectionStrings>
if(Request["connectionToUse"] + "" == "constr1")
return ConfigurationManager.ConnectionStrings["conn1"];
else
return ConfigurationManager.ConnectionStrings["conn2"];
更新:
我不建議寫您的web.config
基於傳入參數 - 這不僅看上去像是會導致安全問題(特別是如果你只是使用在參數傳遞)。
到web.config
任何更改都將重置應用程序,從而導致它的所有用戶下降 - 應用程序池重新啓動的文件發生更改時。
可以有多個連接字符串在你的web.config,並通過它們的名字引用它們:http://weblogs.asp.net/owscott/archive/2005/08/26/Using-connection-strings-from-web.config -in-ASP.NET-v2.0.aspx – jbl 2012-04-10 09:38:24
你想修改web config並更新那裏的現有連接字符串嗎? – Habib 2012-04-10 09:40:56
是habib.osu,這就是我想做的事... – markzzz 2012-04-10 09:43:11