hello world

.net core identityrole

在 .NET Core 中使用 IdentityRole,需要进行以下步骤:

  1. 引入相关 NuGet 包:Microsoft.AspNetCore.Identity.EntityFrameworkCore
  2. 在 DbContext 中添加 IdentityRole:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
public class MyDbContext : IdentityDbContext<ApplicationUser, IdentityRole, string>
{
    public MyDbContext(DbContextOptions<MyDbContext> options)
        : base(options)
    {
    }
}

 

  1. 在 Startup.cs 中配置 Identity:
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<MyDbContext>()
            .AddDefaultTokenProviders();
    services.Configure<IdentityOptions>(options =>
    {
        // 配置密码选项
        options.Password.RequireDigit = true;
        options.Password.RequireLowercase = true;
        options.Password.RequireNonAlphanumeric = true;
        options.Password.RequireUppercase = true;
        options.Password.RequiredLength = 6;
    });
    // 配置 cookie 选项
    services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
        options.LoginPath = "/Account/Login";
        options.LogoutPath = "/Account/Logout";
        options.AccessDeniedPath = "/Account/AccessDenied";
    });
}

 

  1. 在 Controller 中使用 IdentityRole:
using Microsoft.AspNetCore.Identity;
public class MyController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;
    private readonly RoleManager<IdentityRole> _roleManager;
    public MyController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, RoleManager<IdentityRole> roleManager)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _roleManager = roleManager;
    }
    // 创建角色
    public async Task<IActionResult> CreateRole()
    {
        var result = await _roleManager.CreateAsync(new IdentityRole("Admin"));
        return Ok(result);
    }
    // 将用户添加到角色中
    public async Task<IActionResult> AddUserToRole(string userId)
    {
        var user = await _userManager.FindByIdAsync(userId);
        var result = await _userManager.AddToRoleAsync(user, "Admin");
        return Ok(result);
    }
    // 从角色中移除用户
    public async Task<IActionResult> RemoveUserFromRole(string userId)
    {
        var user = await _userManager.FindByIdAsync(userId);
        var result = await _userManager.RemoveFromRoleAsync(user, "Admin");
        return Ok(result);
    }
}

 

posted @ 2023-04-04 08:49  LiveCoding  阅读(68)  评论(0)    收藏  举报