MVC 5 AddToRole需要注销它工作过吗? [英] MVC 5 AddToRole requires logout before it works?
问题描述
我发现,如果我将用户添加到在ASP中身份的作用,它没有,直到我注销并重新登录才能生效。有什么我需要做的刷新用户的角色,不强制用户先注销?
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);
然后,几乎立刻,我将用户重定向到这个操作方法。我可以说我已经加入到正确的角色数据库中告诉我们,但仍MVC我重定向到登录页面。不过,如果我注销,重新登录,并尝试去这个操作方法,它工作得很好。
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!
推荐答案
@凯文 - 荣汉斯你的回答使我对正确的答案。这code显示了如何将用户在MVC 5添加到角色,并自动获得该角色生效。
@kevin-junghans your answer lead me to the correct answer. This code shows how to add a user to a role in MVC 5 and to have that role automatically take effect.
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);
这篇关于MVC 5 AddToRole需要注销它工作过吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!