0

I'm trying to get all users with roles I have done it before and it's working in my other web apps and it's the same code. I seeded Default Roles and default user with a role and registered other some users. I get this error :NullReferenceException: Object reference not set to an instance of an object. at line var users = await _userManager.Users.ToListAsync();

I debugged it and the _userManager is null, I tried some solutions and gave the same Exception. so what did I miss?

Program.CS

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.EntityFrameworkCore;
using EmoloyeeSystemApp.Areas.Identity.Data;
using EmployeeSystemApp.Data;

using EmoloyeeSystemApp.Areas;
//using EmoloyeeSystemApp.Migrations
using Microsoft.AspNetCore.Identity.UI.Services;
//using Employee_System.Models;
using Microsoft.Extensions.DependencyInjection;
using System;
using EmoloyeeSystemApp.Models;

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<EmployeeSystemAppContext>(options =>
    options.UseSqlServer(connectionString), ServiceLifetime.Scoped);

builder.Services.AddDatabaseDeveloperPageExceptionFilter();



builder.Services.AddDefaultIdentity<EmployeeSystemAppUser>(options =>
{

    options.SignIn.RequireConfirmedAccount = false;
    options.Password.RequireLowercase = false;
    options.Password.RequireUppercase = false;
    options.Password.RequireNonAlphanumeric = false;

})
 .AddRoles<IdentityRole>()
 .AddDefaultUI()
 .AddEntityFrameworkStores<EmployeeSystemAppContext>()
 .AddDefaultTokenProviders();




// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddDbContext<EmployeeSystemAppContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));


//builder.Services.AddAuthorization(options =>
//{

//    //options.AddPolicy("rolecreation", policy => policy.RequireRole("Admin"));
//});



var app = builder.Build();

using (IServiceScope? scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    var loggerFactory = services.GetRequiredService<ILoggerFactory>();
    try
    {
        var context = services.GetRequiredService<EmployeeSystemAppContext>();
        var userManager = services.GetRequiredService<UserManager<EmployeeSystemAppUser>>();
        var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
        await Seeds.SeedRoles(userManager, roleManager);
        await Seeds.SeedUser(userManager, roleManager);

    }
    catch (Exception ex)
    {
        var logger = loggerFactory.CreateLogger<Program>();
        logger.LogError(ex, "An error occurred seeding the DB.");
    }



}


// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();


app.UseEndpoints(endpoints =>
{
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();

});

app.Run();

controller:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using EmoloyeeSystemApp.Areas.Identity.Data;
using EmployeeSystemApp.Models;
using EmoloyeeSystemApp.Areas;

namespace EmployeeSystemApp.Controllers
{
    public class UsersWithRolesController : Controller
    {


        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly UserManager<EmployeeSystemAppUser> _userManager;


        public UsersWithRolesController(RoleManager<IdentityRole> roleManager, UserManager<EmployeeSystemAppUser> userManager)
        {
            roleManager = _roleManager;
            userManager = _userManager;
        }

         
        private async Task<List<string>> GetUserRoles(EmployeeSystemAppUser user)
        {
            return new List<string>(await _userManager.GetRolesAsync(user));
        }




        //get all users with thier were assigned roles
        
        public async Task <IActionResult> Index()
        {
            var  users  =  await  _userManager.Users.ToListAsync();
            var usersRoles = new List<UsersWRoles>();

            foreach(EmployeeSystemAppUser user in users)
            {
                var details = new UsersWRoles();
                details.UserId = user.Id;
                details.FirstName = user.FirstName;
                details.LastName = user.LastName;
                details.UserName = user.UserName;
                details.Roles = await GetUserRoles(user);
            }




            return View(usersRoles);
        }



        public async Task<IActionResult> Manage(string userId)
        {
            //Get the user by Id 
            ViewBag.userId = userId;
            var user = await _userManager.FindByIdAsync(userId);

            //define of UserName
            ViewBag.UserNanme = user.UserName;


            // catch the possibility that there is no userId 
            if (user == null)
            {
                ViewBag.Erorr = $"User with Id = {userId} cannot be found";
                return View("cannot be found");
            }



            var model = new List<ManageUsersAndRoles>();

            foreach (var role in _roleManager.Roles)
            {
                //define constructor based on "ManageUsersAndRoles" Model
                var usersRolesManage = new ManageUsersAndRoles()
                {
                    RoleId = role.Id,
                    RoleName = role.Name
                };

                if (await _userManager.IsInRoleAsync(user, role.Name))
                {
                    usersRolesManage.Selected = true;
                }
                else
                {
                    usersRolesManage.Selected = false;
                }

                model.Add(usersRolesManage);
            }

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Manage(List<ManageUsersAndRoles> model, string userId)
        {
            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {

                return View();
            }

            var roles = await _userManager.GetRolesAsync(user);
            var result = await _userManager.RemoveFromRolesAsync(user, roles);

            if (!result.Succeeded)
            {
                ModelState.AddModelError("", "Cannot remove user's existing roles");
                return View(model);
            }
            result = await _userManager.AddToRolesAsync(user, model.Where(x => x.Selected).Select(y => y.RoleName));
            if (!result.Succeeded)
            {
                ModelState.AddModelError("", "Cannot add selected roles to user");
                return View(model);
            }

            return RedirectToAction("Index");

        }


    }
}


      
   

Model:

namespace EmployeeSystemApp.Models
{
    public class UsersWRoles
    {

        public string UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string UserName { get; set; }

        
        public IEnumerable<string> Roles { get; set; }

    }
}
ha33
  • 162
  • 1
  • 5
  • 16

1 Answers1

0

it was a mistake in the controller in the constructor

_userManager = userManager;

it was backwards so I preferred to change the constructor to be :

private readonly UserManager<EmployeeSystemAppUser> userManager;


        public UsersWithRolesController(RoleManager<IdentityRole> roleManager, UserManager<EmployeeSystemAppUser> userManager)
        {
            
            this.userManager = userManager;
        }

and Add a missing line here to be :

foreach (EmployeeSystemAppUser user in users)
            {
                var details = new UsersWRoles();
                details.UserId = user.Id;
                details.FirstName = user.FirstName;
                details.LastName = user.LastName;
                details.UserName = user.UserName;
                details.Roles = await GetUserRoles(user);
                usersRoles.Add(details);
            }
ha33
  • 162
  • 1
  • 5
  • 16