在ASP.NET 2.2中,可以使用Identity来管理用户角色。下面是一个解决用户角色问题的代码示例:
services.AddDefaultIdentity()
.AddRoles()
.AddEntityFrameworkStores();
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions options)
: base(options)
{
}
}
app.UseAuthentication();
app.UseAuthorization();
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
[Authorize(Roles = "Admin")]
public class UserController : Controller
{
private readonly UserManager _userManager;
private readonly RoleManager _roleManager;
public UserController(UserManager userManager, RoleManager roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
}
public IActionResult Index()
{
var users = _userManager.Users.ToList();
return View(users);
}
public async Task AddRole(string userId, string roleName)
{
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return NotFound();
}
await _userManager.AddToRoleAsync(user, roleName);
return RedirectToAction("Index");
}
public async Task RemoveRole(string userId, string roleName)
{
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return NotFound();
}
await _userManager.RemoveFromRoleAsync(user, roleName);
return RedirectToAction("Index");
}
}
上述代码中,[Authorize(Roles = "Admin")]用于指定只有具有"Admin"角色的用户才能访问UserController中的方法。
@model IEnumerable
@foreach (var user in Model)
{
@user.UserName
Roles: @string.Join(", ", await UserManager.GetRolesAsync(user))
}
上述代码中,使用了asp-action和asp-route-userId来指定表单提交的目标方法和参数。
这样,用户角色问题的解决方法就完成了。通过上述代码示例,可以实现用户角色的添加和移除,并在View中显示用户的角色信息。