2015-05-31 33 views
2

今天我来到了我的世界。 基本上,我使用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) 
+0

你为什么要创建一个'AccountController'的新实例?为什么不直接调用'SignInAsync'然后重定向呢? –

+0

是的,我应该从一开始就这样做!谢谢 – MasterJohn

回答

1

当你使用async/await时,工作被卸载到另一个线程。 HttpContext为null的原因是因为您不再处于请求线程中,因此当前的HttpContext实例无法访问(线程静态)。

要确认,请移除异步/等待并尝试。

作为快速解决方法,您可以将对AuthenticationManager的引用作为参数参数传递。

+0

我已经将引用发送给AuthenticationManager,它作为一个快速修复工具。 – MasterJohn