2012-04-10 41 views
1

出頭喜歡:由於請求參數,我可以更改web.config連接字符串嗎?

if(Request["connectionToUse"] + "" == "constr1") 
    // use a connection string 1 
else 
    // use a connection string 2 

是有可能的.NET?

+0

可以有多個連接字符串在你的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

+0

你想修改web config並更新那裏的現有連接字符串嗎? – Habib 2012-04-10 09:40:56

+0

是habib.osu,這就是我想做的事... – markzzz 2012-04-10 09:43:11

回答

1

編輯:這可能是一個非常糟糕的主意,因爲由俄德說,但如果你真的想那麼:

修改基於請求參數看下面的例子中,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 
+0

但這是一個糟糕的主意,因爲應用程序池將在「保存」中重置。 – Oded 2012-04-10 09:44:47

+0

@Oded,是的,但這就是他想要的 – Habib 2012-04-10 09:45:22

+0

@Oded說:「任何對web.config的更改都會重置應用程序,導致其所有用戶都被刪除 - 應用程序池在文件更改時重新啓動。」你的代碼會遭受這個問題嗎? – markzzz 2012-04-10 09:47:14

2

有你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任何更改都將重置應用程序,從而導致它的所有用戶下降 - 應用程序池重新啓動的文件發生更改時。

+0

我認爲他想修改@ habib.osu在web配置 – Habib 2012-04-10 09:40:34

+0

連接 - 閱讀問題的細節。我認爲很顯然,OP要根據傳入的參數使用_different_連接字符串。 – Oded 2012-04-10 09:41:37

+0

是的!我想只有1個在webconfig連接字符串...它編輯因請求PARAM,由habib.osu – markzzz 2012-04-10 09:42:19

相關問題