.net MVC添加角色并添加用户并向用户添加角色+使视图的一部分仅对角色可见

时间:2016-08-25 02:04:45

标签: .net asp.net-mvc user-roles

我是.net的新手,必须为学校创建一个项目。我使用的是MVC 5模板,它有标准登录,但现在我需要2个角色:学生和老师。我如何以及在何处创建这些角色?然后我如何制作它,以便只有登录的人可以使用此导航中的最后一项

<div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li>@Html.ActionLink("Home", "Index", "Home")</li>
                <li>@Html.ActionLink("Roles", "Index", "Roles")</li>
                <li>@Html.ActionLink("Evaluaties", "About", "Home")</li>
            </ul>
            @Html.Partial("_LoginPartial")
        </div>

另外,我想让一个角色看到另一个角色,我该怎么做?

2 个答案:

答案 0 :(得分:3)

MVC5项目模板默认没有角色管理器, 所以我们首先创建我们的角色管理器类; (为了保持项目结构良好,最好添加如下所述的类):

1-创建ApplicationRole类(添加到Models文件夹下的IdentityModels.cs)

public class ApplicationRole : IdentityRole
{
    public ApplicationRole() : base() { }

    public ApplicationRole(string name) : base(name) { }
}

2-创建ApplicationRoleManager类(将其放在App_Start文件夹下的IdentityConfig.cs中)

public class ApplicationRoleManager : RoleManager<ApplicationRole>, IDisposable
{
    public ApplicationRoleManager(RoleStore<ApplicationRole> store) : base(store) { }

    public static ApplicationRoleManager Create(
        IdentityFactoryOptions<ApplicationRoleManager> options,
        IOwinContext context)
    {
        return new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
    }
}

3-在应用程序启动时配置角色管理器;将以下行添加到Startup.Auth.cs文件中的ConfigureAuth(IAppBuilder应用程序)方法:

app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

4-如果需要创建一个新控制器或使用现有控制器,并在控制器构造函数中定义ApplicationuserManager和ApplicationRoleManager的参数,然后从owin上下文中检索身份管理器:

    namespace UsersAndRoles.Controllers
{
using Microsoft.AspNet.Identity.Owin;
using System.Web;
using System.Web.Mvc;

    public class UsersAndRolesController : Controller
    {
        private ApplicationUserManager _userManager;
        private ApplicationRoleManager _roleManager;

        public UsersAndRolesController() { }

        public UsersAndRolesController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
        {
            UserManager = userManager;
            RoleManager = roleManager;
        }

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

        public ApplicationRoleManager RoleManager
        {
            get
            {
                return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
            }
            private set
            {
                _roleManager = value;
            }
        }

        // GET: UsersAndRoles
        public ActionResult Index()
        {
            return View();
        }
    }
}

现在完成设置,控制器已准备好创建用户和角色, 为了创建用户只需创建一个ApplicationUser并使用UserManager.Create方法添加它,密码必须与ApplicationUserManager类中定义的规则匹配。

5-通过调用UserManager.Create方法创建用户:

var user = new ApplicationUser
        {
            UserName = "Ziyad",
            Email = "email@domainname.com"
        };

        var password = "P@ssw0rd";
        UserManager.Create(user, password);

6-使用RoleManager以类似的方式创建角色:

var role = new ApplicationRole
        {
            Name = "Students"
        };

        RoleManager.Create(role);

7-最后一部分是使用UserManager为用户分配角色:

UserManager.AddToRole("user_id", "role_name");

完整的控制器在这里:

    namespace UsersAndRoles.Controllers
{
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.Owin;
    using System.Web;
    using System.Web.Mvc;
    using Models;
public class UsersAndRolesController : Controller
{
    private ApplicationUserManager _userManager;
    private ApplicationRoleManager _roleManager;

    public UsersAndRolesController() { }

    public UsersAndRolesController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
    {
        UserManager = userManager;
        RoleManager = roleManager;
    }

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

    public string CreateUser()
    {
        var user = new ApplicationUser
        {
            UserName = "Ziyad",
            Email = "email@domainname.com"
        };

        var password = "P@ssw0rd";
        var result = UserManager.Create(user, password);

        if (result.Succeeded)
        {
            return "User created";
        }
        else
        {
            var msg = "Error, user not created";
            foreach (var err in result.Errors)
                msg += err + "<br />";

            return msg;
        }            
    }

    public string CreateRole()
    {
        var role = new ApplicationRole
        {
            Name = "Teachers"
        };

        var result = RoleManager.Create(role);

        if (result.Succeeded)
        {
            return "Role created";
        }
        else
        {
            var msg = "Error, role not created";
            foreach (var err in result.Errors)
                msg += err + "<br />";

            return msg;
        }
    }

    public string AddUserToRole()
    {
        var user = UserManager.FindByEmail("email@domainname.com");

        if (user != null)
        {
            var result = UserManager.AddToRole(user.Id, "Teachers");
            if (result.Succeeded)
            {
                return "User assigned to role";
            }
            else
            {
                var msg = "Error, user not assigned to role <br />";
                foreach (var err in result.Errors)
                    msg += err + "<br />";

                return msg;
            }
        }
        else
        {
            return "User not found!";
        }
    }
}

}

如果要将某些视图/菜单限制为特定角色,请使用User.IsInRole(“role_name”)方法:

if (User.IsInRole("Teachers"))
        {
            // role specific options
        }

如果您只想允许特定角色访问操作方法,请使用authorize属性:

[Authorize(Roles = "Teachers")]
public ActionResult ActionName()
{
    //teachers specific method
}

希望这有助于:)

答案 1 :(得分:0)

您可以将角色保存在数据库中,并且在用户成功登录后,您可以在身份验证cookie中添加角色。请参阅我的回答here