今天我来到了我的世界。 基本上,我使用EntityFramework中包含的默认ApplicationUserContext,并且在向用户添加角色时,主题需要注销角色以更新。事实上,这是正常的,因为角色存储在cookie中,每隔30分钟或用户每次登录时加载信息。实体框架中的ApplicationUserContext为null
所以在我的情况下,我试图将特定角色添加到用户,使用角色管理器,然后强制“辞职”,即注销然后登录。
_userManager.AddToRole(UserID, "the role of the world");
ApplicationUser theUser = _userManager.FindById(User.Identity.GetUserId());
if (returnUrl != null)
{
AccountController ac = new AccountController();
await ac.Relogin(theUser);
return Redirect(returnUrl);
}
现在你看,我创建的AccountController的新实例,因为我是在其他控制器和调用的方法“重新登录(用户)”
public async Task Relogin(ApplicationUser _user)
{
await SignInAsync(_user, false);
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
}
现在,当我运行代码,我得到的错误“对象引用不设置到对象的实例在此代码:
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
这基本上意味着我的HttpContext为空...我尝试甚至还让HttpContext的在我的控制器的d以这样的参数发送。它在控制器中不是null,但一旦它进入AccountController,userManager变为空......发生了什么?
public async Task Relogin(ApplicationUserManager _userManager)
你为什么要创建一个'AccountController'的新实例?为什么不直接调用'SignInAsync'然后重定向呢? –
是的,我应该从一开始就这样做!谢谢 – MasterJohn