In MVC5 how can I create user records in code?

╄→гoц情女王★ 提交于 2019-12-25 15:55:38

问题


VS2013, MVC5, VB

The MVC5 template works well to create new users from the Register View while the application is running. But if I want to create users in code, how do I do that?

The following is naïve code, but demonstrates what doesn't work:

Dim user = New ApplicationUser() With {.UserName = "name@live.com", .Email = "name@live.com"}
Dim acct As New AccountController
acct.UserManager.CreateAsync(user, "Temp1.11")

This doesn't work because there is no HttpContext for UserManager.

There's a lot going on here that I don't understand and I'm a little lost. What I set out to do was simply create a list of users using the seed method in Configuration.vb. I thought I could just copy the way the existing AccountController.Register method works, but obviously not.

The answer to my question would ultimately be how to create users in the seed, but I'd like to also understand why my thinking was so wrong about simply trying to use portions of the code from the Register method. I don't quite understand the HttpContext and how that comes into being.


回答1:


You don't need to use AccountController to get access to the UserManager object. Instead just create that directly:

Dim user = New ApplicationUser() With {.UserName = "name@live.com", .Email = "name@live.com"}
Dim myUserManager As New UserManager()
myUserManager.CreateAsync(user, "Temp1.11")


来源:https://stackoverflow.com/questions/28801063/in-mvc5-how-can-i-create-user-records-in-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!