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("DefaultConnection", "UserProfile", "UserId", "UserName", 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()) { UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower()); // 檢查使用者是否存在 if (user == null) { // 將名稱插入設定檔表格 db.UserProfiles.Add(new UserProfile { UserName = 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); }