Just learn ASP.NET Core Identity and try to apply.
But I got this There is already an open DataReader associated with this Connection which must be closed first.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
string connectionString = Configuration.GetConnectionString("default");
services.AddDbContext<AppDBContext>(c => c.UseSqlServer(connectionString));
services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<AppDBContext>();
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Account/Login";
});
services.AddMvc().AddJsonOptions(o =>
{
o.JsonSerializerOptions.PropertyNamingPolicy = null;
o.JsonSerializerOptions.DictionaryKeyPolicy = null;
});
services.AddControllersWithViews();
}
AdministrationController
namespace IspdHelpDesk.Controllers
{
public class AdministrationController : Controller
{
private readonly RoleManager<IdentityRole> roleManager;
private readonly UserManager<IdentityUser> userManager;
private readonly ILogger<AdministrationController> logger;
public AdministrationController(RoleManager<IdentityRole> roleManager,
UserManager<IdentityUser> userManager,
ILogger<AdministrationController> logger)
{
this.roleManager = roleManager;
this.userManager = userManager;
this.logger = logger;
}
[HttpGet]
public IActionResult CreateRole()
{
return View();
}
[HttpPost]
public async Task<IActionResult> CreateRole(CreateRoleViewModel model)
{
if (ModelState.IsValid)
{
IdentityRole identityRole = new IdentityRole
{
Name = model.RoleName
};
IdentityResult result = await roleManager.CreateAsync(identityRole);
if (result.Succeeded)
{
return RedirectToAction("ListRoles", "Administration");
}
foreach (IdentityError error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
return View(model);
}
[HttpGet]
public IActionResult ListRoles()
{
var roles = roleManager.Roles;
return View(roles);
}
[HttpGet]
public async Task<IActionResult> EditRole(string id)
{
var role = await roleManager.FindByIdAsync(id);
if (role == null)
{
ViewBag.ErrorMessage = $"Role with Id = {id} cannot be found";
return View("NotFound");
}
var model = new EditRoleViewModel
{
Id = role.Id,
RoleName = role.Name
};
foreach (var user in userManager.Users)
{
if (await userManager.IsInRoleAsync(user, role.Name))
{
model.Users.Add(user.UserName);
}
}
return View(model);
}
}
}
How to solve - There is already an open DataReader associated with this Connection which must be closed first ?