[英]How to programmatically create users in asp.net 5 using identity
I´m trying to create some users in a seed method, but no luck. 我试图用种子方法创建一些用户,但没有运气。
I had used this example: How to add role and Users in asp.net mvc 5? 我曾经使用过这个例子: 如何在asp.net mvc 5中添加角色和用户? but the
UserManager
seams to be instantiate in a different way. 但
UserManager
接缝以不同的方式实例化。
Looking in the AccountController
, this instance is loaded in the constructor: 查看
AccountController
,此实例将在构造函数中加载:
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
BennerCliContext applicationDbContext)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_applicationDbContext = applicationDbContext;
}
But my seed method lies on the MyDbContext
class. 但我的种子方法在于
MyDbContext
类。
How can I access the UserManager
instance from there? 如何从那里访问
UserManager
实例?
There are another ways to create users in vnext ? 还有其他方法可以在vnext中创建用户吗?
After @Vladislav Karamfilov suggestion: 在@Vladislav Karamfilov建议之后:
Since user manager already had been registered in ASP.NET5's service provider you could easily get instance of user manager by calling following method: 由于用户管理器已经在ASP.NET5的服务提供程序中注册,因此您可以通过调用以下方法轻松获取用户管理器的实例:
var userManager=new HttpContextAccessor()
.HttpContext.ApplicationServices.GetService(typeof(UserManager<ApplicationUser>));
You should create an instance of UserManager<ApplicationUser>
and then use the CreateIdentity
method to create an ApplicationUser
object. 您应该创建
UserManager<ApplicationUser>
的实例,然后使用CreateIdentity
方法创建ApplicationUser
对象。 However if you assign Administrator role to the created user and your code is public be really careful not to expose your site's security . 但是,如果您为创建的用户分配管理员角色并且您的代码是公开的,请务必小心不要暴露您网站的安全性 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.