【发布时间】:2016-02-11 19:10:56
【问题描述】:
好吧,首先我只想说我想做的事竟然是一个真正的 PITA。我遇到的问题类似于以下帖子:
ASP.NET Identity check user roles is not working
Updating user role using asp.net identity
public async Task<ActionResult> MyAccount()
{
var userId = User.Identity.GetUserId();
var user = await UserManager.FindByIdAsync(userId);
if (!User.IsInRole(RoleConst.EXPIRED))
{
await UserManager.AddToRoleAsync(userId, RoleConst.EXPIRED);
await SignInAsync(user, false);
}
var isExpired = User.IsInRole(RoleConst.EXPIRED); // FALSE!!
return View(model);
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
}
按照其他用户的建议,即使在使用登录方法刷新 cookie 后,角色也不会更新。当然角色在数据库中更新。
此代码在更新后检查角色时有效:
var isExpired = UserManager.IsInRole(userId, RoleConst.EXPIRED);
我想我会很好,但是,我需要在我的剃刀视图中立即进行此检查。我还没有找到如何在控制器之外使用 UserManger。对这个看似简单的任务的任何建议将不胜感激!
编辑
我还尝试了以下产生相同结果的方法:
await UserManager.AddToRoleAsync(user.Id, RoleConst.EXPIRED);
await UserManager.UpdateSecurityStampAsync(user.Id);
var isExpired = User.IsInRole(RoleConst.EXPIRED); // FALSE
【问题讨论】:
标签: asp.net-mvc razor identity