如何根据web.config中的登录详细信息读取多个连接字符串 [英] how to read multiple connectionstring depending upon login details from web.config
问题描述
我有一个使用4.5的asp.net web应用程序,以及ms sql server 2012作为后端
,它有五个不同的数据库,每个不同的登录凭证存储在一个表中
我在web.config中有五个不同的连接字符串
Hi,i have a asp.net web application using 4.5 ,and ms sql server 2012 as backend
which has five different database with each different login credential stored in a table
I have five different connection string in web.config as
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
<add name="MainConnStr" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
etc
用户将输入登录凭证,我希望根据登录凭据,用户将连接到他/她的数据库。项目。
为此我在注册按钮点击事件中使用会话对象如
etc
User will enter there login credential and i want depending upon login credential user will be connected to his/her database throughout the project.
For this i have use session object like
in signup button click event
if(user=="local")
session["connectionstring"]="LocalSqlServer"
else
{
session["connectionstring"]="MainConnStr";
}
并在我的申请表中使用此会话对象
and use this session object throughout my application like this
string strcon = ConfigurationManager.ConnectionStrings[""+session["connectionstring"]+""].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
con.Open();
以上代码对我有用对我的要求,但我有一个非常大的项目,
有没有更好的方法来实现我的要求或我应该坚持上述解决方案。
请有人为我提供更好的方法或解决方案来处理这种情况。
the above code is working for me as per to my required but i have a very big project ,
Is there any better approach to achieve My requirement or should i have to stick to the above solution.
Please someone provide me the better approach or solution to deal with this kind of scenario.
推荐答案
似乎正确。一对建议。
1.在阅读null
>会话。
2.不要在任何地方编写连接代码,而是声明为一个新类的属性。当您需要连接字符串时,只需实例化该类。因此,会话检查代码只会出现在该类构造函数或方法中。
Seems correct. Couple of suggestions.
1. You should always check fornull
, before reading theSession
.
2. Instead of writing the connection code everywhere, declare as a property of one new class. When you require the connection string, just instantiated the class. Thus, the session checking codes will only be present inside that class constructor or a method.
这篇关于如何根据web.config中的登录详细信息读取多个连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!