2015-05-07 59 views
0

我有以下代碼嘗試在註冊後自動登錄用戶,但由於某種原因它不起作用。ASP.Net Identity Framework登錄後註冊

的代碼打行:

   return RedirectToAction("Index", "Home"); 

但出於某種原因仍然無法登錄的用戶我以爲SignInAsync會做。

任何人都知道爲什麼它不會自動記錄用戶?

// POST: /Account/Register 
    [HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> Register(RegisterViewModel model) 
    { 
     if (ModelState.IsValid) 
     { 
      var user = new ApplicationUser() { 
       UserName = model.Email, 
       Email = model.Email, 
       FirstName = model.FirstName, 
       LastName = model.LastName, 
       PasswordHint = model.PasswordHint, 
       EmailConfirmed = true 
      }; 
      IdentityResult result = await UserManager.CreateAsync(user, model.Password); 
      if (result.Succeeded) 
      { 
       await SignInAsync(user, false); 

       UserManager.AddToRole(user.Id, AppConstants.Roles.Candidate); 

       //create a candidate profile for this candidate. 
       ApplicationDbContext context = new ApplicationDbContext(); 

       var savedUser = context.Users.Single(x => x.Email == user.Email); 

       savedUser.Candidate = new Candidate(); 

       try 
       { 
        context.SaveChanges(); 
       } 
       catch (DbEntityValidationException e) 
       { 
        foreach (var eve in e.EntityValidationErrors) 
        { 
         Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", 
          eve.Entry.Entity.GetType().Name, eve.Entry.State); 
         foreach (var ve in eve.ValidationErrors) 
         { 
          Console.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"", 
           ve.PropertyName, 
           eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName), 
           ve.ErrorMessage); 
         } 
        } 
        throw; 
       } 

       await SignInAsync(user, isPersistent: false); 
       return RedirectToAction("Index", "Home"); 
      } 
      else 
      { 
       AddErrors(result); 
      } 
     } 

     // If we got this far, something failed, redisplay form 
     return View(model); 
    } 
+1

將用戶添加到角色後使用'UserManager.Update(user);'。另外,您在代碼中登錄用戶兩次。 –

+1

感謝Jacob修復它。它必須已登錄用戶,但未將其與適當的角色關聯,然後重定向到登錄頁面。你可以把你的答覆作爲答案,以便我可以讚美嗎? – Burt

回答

1

添加或改變角色或權利要求時,將UserManager不會自動直到UserManager.Update(user);稱爲堅持這些更改。