I have a list of users, and I want to select a user and create an account for him. I'm using IdentityUser, but I can't insert data in my table dbo.AspNetUsers
I will be glad for any help, thanks
This the controller:
namespace PFE_Management.Controllers
{
public class StudentsController : Controller
{
//Injection des dependances
private readonly ApplicationDbContext _context;
private readonly UserManager<IdentityUser> _userManager;
private SignInManager<IdentityUser> _signManager;
public StudentsController(ApplicationDbContext context,
UserManager<IdentityUser> user,
SignInManager<IdentityUser> signManager)
{
_context = context;
_userManager = user;
_signManager = signManager;
}
// some code here
[HttpPost]
public async Task<IActionResult> Register(Student model)
{
if (ModelState.IsValid)
{
var user = new IdentityUser { Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await _signManager.SignInAsync(user, false);
return RedirectToAction("Index", "Student");
}
else
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
}
return View();
}
}
}
The biggest problem I see is that you don't have UserName. Although all Microsoft tutorials use email for both user name and email fields - you have to assign both:
IdentityUser user = new()
{
UserName = model.email,
Email = model.email,
EmailConfirmed = true
};
IdentityResult result = await _userManager.CreateAsync(user, model.password);
Also, if you still have an issue - please post the error that you are getting from CreateAsync()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.