如何将ASP.NET网站连接到不同的数据库?

时间:2016-06-29 08:57:35

标签: c# asp.net sql-server entity-framework ef-migrations

我初步道歉可能会问一个已经回答的问题,在这种情况下,请引导我到相关的帖子,但我找不到自己的答案。

我有一个ASP.NET网站 - 在发布后 - 应该能够根据用户的意愿连接到不同的数据库。在“登录”页面中,应该有一个数据库列表,用户将从中选择并根据个人凭据连接到一个数据库。这是登录页面的外观:

enter image description here

登录页面的代码:

public partial class Login : Page
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            List<String> conns = new List<string>();
            foreach (ConnectionStringSettings conn in System.Configuration.ConfigurationManager.ConnectionStrings)
            {
                conns.Add(conn.Name);
            }
            listBD.DataSource = conns;
            listBD.DataBind();
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterHyperLink.NavigateUrl = "Register";
            ForgotPasswordHyperLink.NavigateUrl = "Forgot";
            OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
            var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
            if (!String.IsNullOrEmpty(returnUrl))
            {
                RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
            }
            if (User.Identity.IsAuthenticated && this.Request.RawUrl.Contains("Login?"))
            {
                Response.Redirect("~/Interzis.aspx");
            }

            else if (User.Identity.IsAuthenticated && this.Request.RawUrl.Contains("Login"))
            {
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            ApplicationDbContext db = new ApplicationDbContext();
        }

        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
                var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

                List<ApplicationUser> us = manager.Users.ToList();

                foreach (var user in us)
                {
                    textSuccess.Text += user.UserName + ": ";
                    foreach (var role in user.Roles)
                    {
                        textSuccess.Text += role.RoleId + ", ";
                    }
                }
                var result = signinManager.PasswordSignIn(Email.Text, Password.Text, true, shouldLockout: false);

                switch (result)
                {
                    case SignInStatus.Success:
                        panelSuccess.Visible = true;
                        IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                        break;
                    case SignInStatus.LockedOut:
                        Response.Redirect("/Account/Lockout");
                        break;
                    case SignInStatus.RequiresVerification:
                        Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}", 
                                                        Request.QueryString["ReturnUrl"],
                                                        RememberMe.Checked),
                                          true);
                        break;
                    case SignInStatus.Failure:
                    default:
                        FailureText.Text = "Înregistrare eșuată";
                        ErrorMessage.Visible = true;
                        break;
                }
            }
        }
    }

Startup类:

public partial class Startup {

        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login.aspx"),
                Provider = new CookieAuthenticationProvider
                {

                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });

        }

}

这是我目前简化版的DBContext类:

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {

        public ApplicationDbContext()
            : base("Users", throwIfV1Schema: false)
        {
            Configuration.ProxyCreationEnabled = true;
            Configuration.LazyLoadingEnabled = true;
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        // Override OnModelsCreating:
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            System.Data.Entity.Database.SetInitializer<ApplicationDbContext>(null);
        }

    }

如果我将连接字符串参数添加到ApplicationDbContext构造函数中,我需要在启动类中添加它:

app.CreatePerOwinContext(() => ApplicationDbContext.Create(connectionString));

但是在单击“登录”页面上的“提交”按钮之前会调用此方法,因此在选择数据库之前。这意味着应该有一个应用程序首先尝试连接的默认数据库。但这不是我想要的。 我怎么能改变这种情况呢?

其次,我应该在Login类中添加哪些代码来连接到选定的数据库?

我将添加我使用Entity Framework 6和Code First Migrations来处理数据库。

非常感谢!

0 个答案:

没有答案
相关问题