如何在ASP.NET Core中创建角色并将其分配给用户 [英] How to create roles in asp.net core and assign them to users

查看:357
本文介绍了如何在ASP.NET Core中创建角色并将其分配给用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用asp.net核心默认网站模板和身份验证作为单个用户帐户.如何创建角色并将其分配给用户,以便可以在控制器中使用角色来过滤访问权限.

I am using asp.net core default web site template and authentication selected as individual user account. How can I create role and assign it to user so that I can use role in controller to filter the access.

推荐答案

我在帐户控制器中创建了一个操作,该操作调用一个函数来创建角色并影响默认用户的admin角色(您可能应该删除默认用户在生产中):

I created a action in the account controller that call a function to create the roles and affect the admin role to a default user (You should probably remove the default user in production):

    private async Task createRolesandUsers()
    {  
        bool x = await _roleManager.RoleExistsAsync("Admin");
        if (!x)
        {
            // first we create Admin rool    
            var role = new IdentityRole();
            role.Name = "Admin";
            await _roleManager.CreateAsync(role);

            //Here we create a Admin super user who will maintain the website                   

            var user = new ApplicationUser();
            user.UserName = "default";
            user.Email = "default@default.com";

            string userPWD = "somepassword";

            IdentityResult chkUser = await _userManager.CreateAsync(user, userPWD);

            //Add default User to Role Admin    
            if (chkUser.Succeeded)
            {
                var result1 = await _userManager.AddToRoleAsync(user, "Admin");
            }
        }

        // creating Creating Manager role     
        x = await _roleManager.RoleExistsAsync("Manager");
        if (!x)
        {
            var role = new IdentityRole();
            role.Name = "Manager";
            await _roleManager.CreateAsync(role);
        }

        // creating Creating Employee role     
        x = await _roleManager.RoleExistsAsync("Employee");
        if (!x)
        {
            var role = new IdentityRole();
            role.Name = "Employee";
            await _roleManager.CreateAsync(role);
        }
  }

之后,您可以创建控制器来管理用户的角色.

After you could create a controller to manage roles for the users.

这篇关于如何在ASP.NET Core中创建角色并将其分配给用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆