我正在使用 VS 2015 运行 ASP.net MVC 5
实际上即使ApplicationUserManager 需要OwinContext,你也可以去掉OwinContext。
OwinContext 仅对访问绑定到OWinContext 的ApplicationDbConbtext 有用。
所以我重构了ApplicationUserManager 的Create 工厂方法,以便能够在启动时(或在WebJob 中)管理用户,而无需任何OwinContext:
public static ApplicationUserManager Create(
IdentityFactoryOptions<ApplicationUserManager> options,
IOwinContext context)
{
ApplicationDbContext dbContext = context.Get<ApplicationDbContext>();
return Create(options, dbContext);
}
internal static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, Applicatio
{
// Create ApplicationUserManager myself instead of finding it on OwinContext
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));
// old code already generated by VS wizard
}
然后我使用ApplicationUserManager:
using (ApplicationDbContext applicationDbContext = new ApplicationDbContext())
{
var options = new IdentityFactoryOptions<ApplicationUserManager>
{
//DataProtectionProvider = app.GetDataProtectionProvider(),
};
ApplicationUserManager userManager = ApplicationUserManager.Create(options, applicationDbContext);
// ApplicationRoleManager has been changed the same way to be usable without OwinContext
ApplicationRoleManager appRoleManager = ApplicationRoleManager.Create(applicationDbContext);
// ... Code using ApplicationUserManager and ApplicationRoleManager
ApplicationUser appUser = userManager.FindByEmailAsync(email).Result;
// ...
IdentityResult result = userManager.CreateAsync(appUser, password).Result;
}
}
希望对你有帮助