gpt4 book ai didi

asp.net-mvc-5 - MVC 5 AddToRole 需要注销才能工作吗?

转载 作者:行者123 更新时间:2023-12-02 11:39:19 24 4
gpt4 key购买 nike

我发现,如果我将用户添加到 ASP Identity 中的角色,直到我注销并重新登录后,它才会生效。我需要做些什么来刷新用户的角色而不强制执行用户要先注销吗?

以下是我将用户添加到角色的方法。

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);

关于asp.net-mvc-5 - MVC 5 AddToRole 需要注销才能工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20495249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com