Search code examples
c#asp.net-mvcrazorasp.net-roles

User IsInRole only works after signing in and out from the website


I am adding and removing users from roles in my controller code and in my shared _Layout view, I am using User.IsInRole to check and remove links accordingly but it only works if user signs out of the website then User.IsInRole returns correct result?

Is there a way to reload the _Layout page so it grabs the data correctly?

Controller Code to change roles

  _userManager.RemoveFromRole(obj.strUserID, "Consumer");
  _userManager.AddToRole(obj.strUserID, "Provider");
  _context.SaveChanges();
  return View("Success");

Shared _Layout View which is used by multiple pages

  if (!User.IsInRole("Provider"))
      {
       <li>@Html.ActionLink("Become a Member", "Memmber", "CustProfile")</li>
      }

Once, I remove and add new roles to User, I want _Layout.cstml to show correct links but it does not. It works fine, if I sign out and sign back in.

Is there a way to fix this behavior?


Solution

  • User is cached until log out so you will have to sign them again. Please use the following code to sign them again. Also, make sure to redirect them instead of View so page is reloaded.

     private ApplicationSignInManager _signInManager;
    
     public ApplicationSignInManager SignInManager
            {
                get
                {
                    return _signInManager ?? 
                    HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
                }
                private set
                {
                    _signInManager = value;
                }
            }
    

    Add the following code after changing the roles:

      var userinDb = _context.Users.Find(UserID);
      await SignInManager.SignInAsync(userinDb, true,false);
      return RedirectToAction("Success");