问题描述
我发现如果我将用户添加到 ASP Identity 中的角色,它在我注销并重新登录之前不会生效.我需要做些什么来刷新用户的角色而不强制执行用户先注销?
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!
推荐答案
MVC5 注册新用户,分配角色并使用角色激活用户,无需注销并使用 :await UserManager.AddToRoleAsync(user.Id, "Role Name")
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);
这篇关于MVC 5 AddToRole 需要注销才能工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!