public SimpleMembershipInitializer() { Database.SetInitializer<UsersContext>(null); try { using (var context = new UsersContext()) { if (!context.Database.Exists()) { // 创建不包含 Entity Framework 迁移架构的 SimpleMembership 数据库 ((IObjectContextAdapter)context).ObjectContext.CreateDatabase(); } } WebSecurity.InitializeDatabaseConnection("OB", "User", "Id", "Name", autoCreateTables: true); } catch (Exception ex) { throw new InvalidOperationException("无法初始化 ASP.NET Simple Membership 数据库。有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=256588", ex); } }
public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl) { string provider = null; string providerUserId = null; if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId)) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // 将新用户插入到数据库 using (UsersContext db = new UsersContext()) { User user = db.User.FirstOrDefault(u => u.Name.ToLower() == model.UserName.ToLower()); // 检查用户是否已存在 if (user == null) { // 将名称插入到配置文件表 db.User.Add(new User { Name = model.UserName }); db.SaveChanges(); OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName); OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false); return RedirectToLocal(returnUrl); } else { ModelState.AddModelError("UserName", "用户名已存在。请输入其他用户名。"); } } } ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName; ViewBag.ReturnUrl = returnUrl; return View(model); }