【发布时间】:2022-01-20 14:10:48
【问题描述】:
我正在尝试让所有具有我以前做过的角色的用户,并且它在我的其他网络应用程序中工作并且它是相同的代码。
我为默认角色和默认用户播种了一个角色,并注册了其他一些用户。
我收到此错误:NullReferenceException:对象引用未设置为对象的实例。在线var users = await _userManager.Users.ToListAsync();
我调试它并且 _userManager 为空,我尝试了一些解决方案并给出了相同的异常。 那我错过了什么?
程序.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();
控制器:
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");
}
}
}
型号:
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; }
}
}
【问题讨论】:
-
你能提供你的用户管理器类吗?
-
UserManager 是使用 .AddDefaultIdentity() 注册的,我将 UserManager
_userManager 添加到构造函数中。你是这个意思吗?还是我没听懂? -
roleManager = _roleManager;这是倒退。 -
@JeremyLakeman 这是我犯的一个愚蠢的错误'userManager = _userManager;'倒退了谢谢
-
当你更改
_userManager = userManager;时,项目工作正常吗?
标签: c# asp.net asp.net-mvc asp.net-core asp.net-web-api