예제 #1
0
        public async static Task InitDB(IServiceProvider service)
        {
            // 获取数据库上下文服务
            var DB = service.GetRequiredService<EvaluateContext>();

            // 获取UserManager服务
            var userManager = service.GetRequiredService<UserManager<User>>();

            // 获取RoleManager服务
            var roleManager = service.GetRequiredService<RoleManager<IdentityRole>>();

            if (DB.Database != null && DB.Database.EnsureCreated())
            {
                // 初始化角色
                await roleManager.CreateAsync(new IdentityRole { Name = "系主任" });
                await roleManager.CreateAsync(new IdentityRole { Name = "组长" });
                await roleManager.CreateAsync(new IdentityRole { Name = "学生" });

                // 初始化系主任,并为其添加系主任角色
                var user = new User { Name = "张某某", UserName = "******" };
                await userManager.CreateAsync(user, "Yuuko19931101!@#");
                await userManager.AddToRoleAsync(user, "系主任");
            }
        }
예제 #2
0
        public async Task<IActionResult> CreateStudent(string username, string password, string studentnumber, string Class, string group, string name, string position)
        {
            var user = new User
            {
                UserName = username,
                Group = group,
                Class = Class,
                Name = name,
                StudentNumber = studentnumber
            };

            // 创建用户
            var result = await UserManager.CreateAsync(user, password);

            // 如果没有成功,则返回错误信息
            if (!result.Succeeded)
                return Content(result.Errors.First().Description);

            // 添加角色
            await UserManager.AddToRoleAsync(user, "学生");

            if (position == "组长")
                await UserManager.AddToRoleAsync(user, "组长");

            return RedirectToAction("Student", "Home");
        }