MVC 5 AddToRole requires logout before it works?
asp.net-identity, asp.net-mvc-5
Solution
MVC5 register new user, assign role and activate user with role WITHOUT logging off and back on by using :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);
Problem
I'm finding that if I add a user to a role in ASP Identity, it doesn't take effect until I log out and log back in. Is there something I need to do to refresh a user's roles without forcing a user to log off first? Here's how I'm adding the user to the role. ``` var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var userId = HttpContext.Current.User.Identity.GetUserId(); userManager.AddToRole(userId, roleName); ``` Then, almost immediately, I redirect the user to this action method. I can tell in the database that I've been added to the correct role, but MVC still redirects me to the login page. However, if I log out, log back in, and attempt to go to this action method, it works just fine. ``` [Authorize(Roles = RecoveryStandardRoles.ServiceProvider)] public partial class CertifyController : Controller { #region Public Methods and Operators public virtual ActionResult CompanyProfile() { return this.View(); } #endregion } ``` Thank you for taking time to look at my question!