skip to Main Content

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, @"imagescompany");

                 using (var fileStream = new FileStream(Path.Combine(companyPath, fileName), FileMode.Create))
                 {
                     file.CopyTo(fileStream);
                 }

                 company.CompanyLogo = @"imagescompany" + 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.

2

Answers


  1. 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

    public CompanyController(
        UserManager<ApplicationUser> userManager,
        SignInManager<ApplicationUser> signInManager,
        IUnitOfWork unitOfWork,
        IWebHostEnvironment webHostEnvironment)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _unitOfWork = unitOfWork;
        _webHostEnvironment = webHostEnvironment;
    }
    

    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.

    var connectionString = 
    builder.Configuration.GetConnectionString("DefaultConnection");
    builder.Services.AddDbContext<ApplicationDbContext>(options =>
      options.UseSqlServer(connectionString));
    builder.Services.AddDatabaseDeveloperPageExceptionFilter();
    
    builder.Services.AddDefaultIdentity<ApplicationUser>(options => 
       options.SignIn.RequireConfirmedAccount = true)
      .AddEntityFrameworkStores<ApplicationDbContext>();
    

    You can find more info here – https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-8.0&tabs=visual-studio

    Login or Signup to reply.
  2. Hey can you add the error log or screenshot of error page you get.
    there can be multiple reason for error to occur. error log will help to understand the error.

    according to my knowledge I think this will help:

    var user = new IdentityUser { UserName = company.CompanyEmail, Email = company.CompanyEmail };
    var result = await _userManager.CreateAsync(user, company.CompanyPassword);
    

    Do not add passwordhash to the use it take care of that itself, but username and email are required as they will be used in login and identifying the user.

    Note : email used in User Object will be used in while logging the user

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search