I'm using .NET 7 and I saw some posts about the questions I look for, but no one similar my error and my way to insert the new user inside the AspNetUser table. I have my company controller and I try insert some fields inside the AspNetUser, but the away I get errors. I am showing my controller code - if someone can help I really appreciate.
This is my controller
public class CompanyController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IUnitOfWork _unitOfWork;
private readonly IWebHostEnvironment _webHostEnvironment;
public CompanyController(IUnitOfWork unitOfWork, IWebHostEnvironment webHostEnvironment)
{
_unitOfWork = unitOfWork;
_webHostEnvironment = webHostEnvironment;
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Company company, IFormFile? file)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
Email = company.CompanyEmail,
PasswordHash = company.CompanyPassword,
};
var result = _userManager.CreateAsync(user, company.CompanyPassword).ConfigureAwait(false);
string wwwRootPath = _webHostEnvironment.WebRootPath;
if (file != null)
{
string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
string companyPath = Path.Combine(wwwRootPath, @"images\company");
using (var fileStream = new FileStream(Path.Combine(companyPath, fileName), FileMode.Create))
{
file.CopyTo(fileStream);
}
company.CompanyLogo = @"\images\company\" + fileName;
}
_unitOfWork.Company.Add(company);
_unitOfWork.Save();
TempData["success"] = "Company created successfully.";
return RedirectToPage("/Account/Login", new { area = "Identity" });
}
return View(company);
}
}
In the result, the _usermanager returns null.
From looking at our code the only thing I can think of is you are missing the initialization of user manager and sign manager in your company controller constructor. And that's why it's getting null. You are using dependency injection then you need to inject all things which you want in constructor like this
If you still get user manager null then check your startup.cs or progam.cs files and see you have done proper configuration of asp.net core identity like below.
You can find more info here - https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-8.0&tabs=visual-studio