.net MVC添加角色并添加用户并向用户添加角色+使视图的一部分仅对角色可见 [英] .net MVC add roles and add users and add roles to users + make part of a view only visible for a role

查看:110
本文介绍了.net MVC添加角色并添加用户并向用户添加角色+使视图的一部分仅对角色可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是.net的新手,必须创建一个学校项目.我正在使用MVC 5模板,它具有标准的登录名,但是现在我需要2个角色:学生和老师.如何以及在何处创建这些角色?然后我该如何做,以便只有登录的人才能从该导航中获取最后一个项目

I am new to .net and have to create a project for school. I am using an MVC 5 template and it has a standard login but now I need 2 roles: student and teacher. How and where do I create those roles? And then how do I make it so that only logged in people can the last item from this nav

<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>

另外,我希望一个角色与另一个角色有不同的看法?

Plus I want one role to see a different view from the other how do I do that?

推荐答案

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

MVC5 project template doesn't have role manager by default, so we start by creating our role manager classes; (in order to keep the project well structured it is better to add the classes as mentioned below):

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

1- create ApplicationRole class (add to IdentityModels.cs under Models folder)

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

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

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

2- create ApplicationRoleManager class (put it inside IdentityConfig.cs under App_Start folder)

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)方法中:

3- configure the role manager at application start up; add the below line to the ConfigureAuth(IAppBuilder app) method in Startup.Auth.cs file :

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

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

4- create a new controller if required or use an existing one, and define the parameters for ApplicationuserManager and ApplicationRoleManager inside the controller constructor, then retrieve the identity managers from the owin context:

    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类中定义的规则匹配.

The setup is done now and the controller is ready to create users and roles, in order to create a user simply create an ApplicationUser and add it using UserManager.Create method, the password must match the rules defined in the ApplicationUserManager class.

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

5- create user by calling UserManager.Create method:

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

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

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

6- creating roles in a similar way using RoleManager:

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

        RoleManager.Create(role);

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

7- last part is to assign roles to users using 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 you want to restrict some views/menus to specific roles use User.IsInRole("role_name") method:

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

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

if you want to allow only specific role to access an action method use the authorize attribute:

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

希望这会有所帮助:)

这篇关于.net MVC添加角色并添加用户并向用户添加角色+使视图的一部分仅对角色可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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