jac*_*ric 0 asp.net-mvc entity-framework asp.net-identity
我正在asp.net mvc中开发一个Web应用程序。我的应用程序使用多个数据库。正在使用的数据库取决于登录的用户。我在两个级别上管理登录:
示例:在“主”数据库中,我在用户表中有一条记录,其中包含:-用户名=用户1-databaseToUse =“ specificDb1”
对于同一个用户,在名为“ specificDb1”的“特定”数据库中,我在用户表中有一条记录,其中包含管理用户身份验证所需的全部内容。
我想要实现的是:
第1点和第2点没有问题。问题出在第3点。我对(主数据库和特定数据库)数据库都使用EntityFramework 6 Code First。
关于身份的配置部分,我在Startup.Auth.cs中看到:
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
Run Code Online (Sandbox Code Playgroud)
我应该更改身份配置中的某些内容吗?
提前致谢。
花了几个小时在这里搜索我的个人(也许不是最好的)工作解决方案。
在AccountController的Login操作中,首先签入“ master”数据库后,在Session作用域中设置“ specific”数据库信息:
//Save the database infos in Session.
Session.Add("SqlServerInstance", masterUser.Company.DatabaseServer);
Session.Add("DbName", masterUser.Company.DatabaseName);
Run Code Online (Sandbox Code Playgroud)
始终在AccountController中更新SignInManager和UserManager属性,以修复Identity上下文的连接字符串:
public ApplicationSignInManager SignInManager
{
get
{
//Set manually the right connection string used by the Identity database context.
HttpContext.GetOwinContext().Get<ApplicationDbContext>().Database.Connection.ConnectionString = ApplicationDbContext.GetConnectionString();
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
//Set manually the right connection string used by the Identity database context.
HttpContext.GetOwinContext().Get<ApplicationDbContext>().Database.Connection.ConnectionString = ApplicationDbContext.GetConnectionString();
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
Run Code Online (Sandbox Code Playgroud)
最后是为我们提供连接字符串的方法:
/// <summary>
/// Get the connection string getting SqlServerInstance and DbName from Session.
/// </summary>
public static string GetConnectionString()
{
string sqlServerInstance = DEFAULT_SQLSERVERINSTANCE;
if (HttpContext.Current.Session != null && HttpContext.Current.Session["SqlServerInstance"] != null)
sqlServerInstance = Convert.ToString(HttpContext.Current.Session["SqlServerInstance"]);
string dbName = DEFAULT_DBNAME;
if (HttpContext.Current.Session != null && HttpContext.Current.Session["DbName"] != null)
dbName = Convert.ToString(HttpContext.Current.Session["DbName"]);
return "Data Source=" + sqlServerInstance + ";Initial Catalog=" + dbName + ";Integrated Security=True";
}
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助。