AuthenticationManager HttpContext is Null
本文关键字:Null is HttpContext AuthenticationManager | 更新日期: 2023-09-27 18:11:21
我想在我的控制器中使用这段代码:
IAccountManagementService<User> _service;
public AccountController(IAccountManagementService<User> service)
{
_service = service;
_service.AuthenticationManager = HttpContext.GetOwinContext().Authentication;
_service.UserManager = new UserManager<User>(new UserStore<User>(new DefaultContext()));
}
并且它稍微适应了ASP模板的原始样板代码。. NET MVC 5
它是通过Ninject注入的,Ninject使用依赖解析器和模块加载器:
var kernel = new StandardKernel(new ModuleLoader());
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
所以我不知道这是不是把上下文搞乱了
服务只是将原始代码抽象到其中,服务看起来像这样:
IRepository _repository;
public AccountManagementService(IRepository repository)
{
_repository = repository;
}
public UserManager<User> UserManager { get; set; }
public IAuthenticationManager AuthenticationManager { get; set; }
public RoleManager<IdentityRole> RoleManager { get; set; }
原始代码看起来像这样:
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
public UserManager<ApplicationUser> UserManager { get; private set; }
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
我可能会注射IAuthenticationManager
,但还没有真正研究过。
我只是不确定当我加载我的网站,我点击登录,它带我到控制器的构造函数,并指向行开始:_service.AuthenticationManager
,并告诉我,HttpContext
是空的。
我通过重新做所有的Ninject
依赖注入来修复这个问题。我现在遵循Ninject
的约定MVC 5
我为ASP添加了这些绑定。NET身份:
//<----- ACCOUNT STUFF ----->''
kernel.Bind<IUserStore<EbpUser>>().To<UserStore<EbpUser>>().WithConstructorArgument("context", context => kernel.Get<DefaultContext>());
kernel.Bind<IRoleStore<IdentityRole, string>>().To<RoleStore<IdentityRole, string, IdentityUserRole>>().WithConstructorArgument("context", context => kernel.Get<DefaultContext>());
为了得到HttpContext
,我绑定了AuthenticationManager
:
kernel.Bind<IAuthenticationManager>().ToMethod(c => HttpContext.Current.GetOwinContext().Authentication).InRequestScope();
在我的AccountManagementService
中,我现在这样做:
IRepository _repository;
IAuthenticationManager _authManager;
UserManager<EbpUser> _userManager;
RoleManager<IdentityRole> _roleManager;
public AccountManagementService(IRepository repository, IUserStore<EbpUser> userStore, IRoleStore<IdentityRole, string> roleStore, IAuthenticationManager authManager)
{
_repository = repository;
_authManager = authManager;
_userManager = new UserManager<EbpUser>(userStore);
_roleManager = new RoleManager<IdentityRole>(roleStore);
}
所以现在一切都注入正确,它看起来整洁多了