Asp.net-Mvc-5
MVC 5 AddToRole 需要註銷才能工作?
我發現如果我將使用者添加到 ASP 身份中的角色,它在我註銷並重新登錄之前不會生效。我需要做些什麼來刷新使用者的角色而不強制使用者登錄先關?
這是我將使用者添加到角色的方式。
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var userId = HttpContext.Current.User.Identity.GetUserId(); userManager.AddToRole(userId, roleName);然後,幾乎立即,我將使用者重定向到此操作方法。我可以在數據庫中知道我已被添加到正確的角色,但 MVC 仍將我重定向到登錄頁面。但是,如果我註銷、重新登錄並嘗試使用此操作方法,它就可以正常工作。
[Authorize(Roles = RecoveryStandardRoles.ServiceProvider)] public partial class CertifyController : Controller { #region Public Methods and Operators public virtual ActionResult CompanyProfile() { return this.View(); } #endregion }感謝您花時間看我的問題!
MVC5註冊新使用者,分配角色並使用角色啟動使用者而無需註銷並使用以下方法重新登錄:await UserManager.AddToRoleAsync(user.Id, “Role Name”)
if (ModelState.IsValid) { var user = new ApplicationUser() { UserName = model.Email, Email = model.Email,StandName = model.StandName,FirstName = model.FirstName,LastName = model.LastName,CellPhone = model.CellPhone,Supervisor = model.Supervisor}; IdentityResult result = await UserManager.CreateAsync(user, model.Password); var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); if (result.Succeeded) { ***await UserManager.AddToRoleAsync(user.Id, "Users Tammy");*** await SignInAsync(user, isPersistent: false);
@kevin-junghans 你的回答讓我找到了正確的答案。此程式碼顯示如何在 MVC 5 中將使用者添加到角色並讓該角色自動生效。
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var userId = HttpContext.Current.User.Identity.GetUserId(); userManager.AddToRole(userId, roleName); var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var user = userManager.FindById(userId); var identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);