需要关于如何获取/显示用户角色的理解 [英] Need understanding on how to get/display User Role

查看:96
本文介绍了需要关于如何获取/显示用户角色的理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在与身份2 MVC学习的过程,我在拍摄的样本项目和调整,以适合我试图从与ASP.Net成员资格提供程序的WebForms转换网站点。

我在与目前越来越我的头缠着我如何从另一个表获得的值来填充类中的财产问题是什么。

我有一个类叫做AppUser.cs并从IdentityUser继承。该基本上是映射到一个命名为AspNetUsers使用的EntityFramework表。我已经添加了使用EF迁移一对夫妇更多的属性(名字/姓氏),以该表。现在我想显示的用户分配什么样的角色并最终将需要获得可用角色的列表,并将它们添加到一个DropDownList。我加入了角色名属性我APPUSER类,但我假设,因为该数据不存储在AspNetUsers表就是为什么我得到一个错误无效列名'角色名'。

我将如何填充作用和/或得到我APPUSER类可用角色的列表,以便我可以在我查看显示呢?

 公共类APPUSER:IdentityUser
    {
        公共字符串名字{获得;组; }
        公共字符串名字{获得;组; }
        公共字符串角色名{获得;组; }
    }

在ViewIndex.cshtml的模式是APPUSER。

  @model IEnumerable的<&APPUSER GT;

这是我对我的控制器的ActionResult。

 公众的ActionResult指数(){
                返回查看(UserManager.Users);
            }私人AppUserManager的UserManager {
            获得{
                返回HttpContext.GetOwinContext()GetUserManager< AppUserManager>();
            }
        }

这是AppUserManager.cs

 使用Microsoft.AspNet.Identity.Owin;
使用Microsoft.Owin;
使用SampleMvcSite.Models;命名空间SampleMvcSite.Infrastructure {
    公共类AppUserManager:&的UserManager LT; APPUSER> {        公共AppUserManager(IUserStore<&APPUSER GT;存储)
            :基地(商店){
        }        公共静态AppUserManager创建(
                IdentityFactoryOptions< AppUserManager>选项​​,
                IOwinContext上下文){            AppIdentityDbContext DB = context.Get< AppIdentityDbContext>();
            AppUserManager经理=新AppUserManager(新UserStore<&APPUSER GT;(DB));            manager.PasswordValidator =新CustomPasswordValidator {
                RequiredLength = 6,
                RequireNonLetterOrDigit =假,
                RequireDigit =假,
                RequireLowercase = TRUE,
                RequireUppercase =真
            };            manager.UserValidator =新CustomUserValidator(经理){
                AllowOnlyAlphanumericUserNames = TRUE,
                RequireUniqueEmail =真
            };            返回经理;
        }
    }
}

更新时间是code:
我结束了创建一个类调用UserEditViewModel,我也包括这在我调整示例项目的AppRole类。

 公共类UserEditViewModel:IdentityUser
        {
            公共字符串名字{获得;组; }
            公共字符串名字{获得;组; }
            公共字符串的UserRole {搞定;组; }
            公共IEnumerable的< AppRole> AllRoles {搞定;组; }
        }    公共类AppRole:IdentityRole {        公共AppRole():碱(){}        公共AppRole(字符串名称):基地(名){}
    }

然后在我的控制器我做了以下。请记住,我只打算允许用户在同一时间被分配到一个角色所以理论上应该只有这就是为什么我只叫上了的UserRole一个角色[0]。由于我一些样本用户后添加的RoleManager我有没有分配到角色一对夫妇的用户。我添加了一个检查,以确保该角色有一个数,如果没有我显示用户作为自己的角色。我会回去,并添加code真正将用户添加到用户的角色,如果没有角色中找到。

 列表< UserEditViewModel> UserList的=新名单< UserEditViewModel>();            VAR用户= UserManager.Users;
            的foreach(APPUSER用户的用户)
            {
                VAR =的UserRole等待UserManager.GetRolesAsync(user.Id);
                字符串角色名= userRoles.Count()== 0? 用户:的UserRole [0];                UserEditViewModel editUser =新UserEditViewModel();
                editUser.UserName = user.UserName;
                editUser.FirstName = user.FirstName;
                editUser.LastName = user.LastName;
                editUser.Email = user.Email;
                editUser.UserRole =角色名;
                editUser.AllRoles = RoleManager.Roles;
                UserList.Add(editUser);
            }            返回查看(UserList的);

下面是查看

 < D​​IV CLASS =表单组>
        <标签>角色:其中; /标签> @ Html.DisplayNameFor(型号=> model.UserRole)
    < / DIV>


解决方案

我想看看的ViewModels。这是一般不好的做法来更新您的视图的实体模型 - 尤其是与安全相关的实体。见<一href=\"https://www.stevefenton.co.uk/2013/03/Why-You-Never-Expose-Your-Domain-Model-As-Your-MVC-Model/\" rel=\"nofollow\">https://www.stevefenton.co.uk/2013/03/Why-You-Never-Expose-Your-Domain-Model-As-Your-MVC-Model/

通过一个视图模型,你可以为属性列表&LT;作用&GT; ,你在你的控制器填充,并在您的视图和类似角色ID另一个属性,为用户的角色使用

在POST,你会做这样的事情:

 如果(ModelState.IsValid)
{
    VAR roleMgr =新RoleManager&LT; IdentityRole&GT;(新Rolestore的&LT; IdentityRole&GT;(上下文));
    VAR userMgr =新的UserManager&LT; ApplicationUser&GT;(新UserStore&LT; ApplicationUser&GT;(上下文));
    VAR角色= roleMgr.FindById(viewmodel.RoleId);
    如果(角色!= NULL)u​​serMgr.AddToRole(viewmodel.UserId,role.Name);
}

查看:

 &LT; D​​IV CLASS =表单组&GT;
    @ Html.LabelFor(型号=&GT; model.RoleId)
    &LT; D​​IV CLASS =COL-MD-2&GT;
        @ Html.DropDownListFor(型号=&GT; model.RoleId,Model.RoleList,htmlAttributes:新{@class =表格控})
    &LT; / DIV&GT;
    &LT; D​​IV CLASS =COL-MD-10 COL-MD-偏移2&GT;
        @ Html.ValidationMessageFor(型号=&GT; model.RoleId,新{@class =TEXT-危险})
    &LT; / DIV&GT;
&LT; / DIV&GT;

I’m in the process of learning MVC with Identity 2 and I’m at the point of taking a sample project and tweaking it to fit a site that I’m trying to convert from WebForms with ASP.Net Membership provider.

What I’m having issues with at the moment is getting my head wrapped around how I get a value from another table to populate a property in a class.

I have a class called AppUser.cs and it inherits from IdentityUser. That is basically mapped to a table named "AspNetUsers" using EntityFramework. I’ve added a couple more properties (First/Last Name) to that table using EF migrations. Now I want to display what Role the user is assigned to and eventually will need to get a list of the available roles and add them to a dropdownlist. I added the RoleName property to my AppUser class but I’m assuming that since that data is not stored in the AspNetUsers table is why I’m getting an error "Invalid column name 'RoleName'".

How would I populate the Role and/or get a list of available Roles in my AppUser class so I can display it in my View?

public class AppUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string RoleName { get; set; }
    }

The model on the view "Index.cshtml" is the AppUser.

@model IEnumerable<AppUser>

This is my ActionResult for my Controller.

   public ActionResult Index() {
                return View(UserManager.Users);
            }

private AppUserManager UserManager {
            get {
                return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
            }
        }

This is the AppUserManager.cs

using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using SampleMvcSite.Models;

namespace SampleMvcSite.Infrastructure {
    public class AppUserManager : UserManager<AppUser> {

        public AppUserManager(IUserStore<AppUser> store)
            : base(store) {
        }

        public static AppUserManager Create(
                IdentityFactoryOptions<AppUserManager> options,
                IOwinContext context) {

            AppIdentityDbContext db = context.Get<AppIdentityDbContext>();
            AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db));

            manager.PasswordValidator = new CustomPasswordValidator {
                RequiredLength = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit = false,
                RequireLowercase = true,
                RequireUppercase = true
            };

            manager.UserValidator = new CustomUserValidator(manager) {
                AllowOnlyAlphanumericUserNames = true,
                RequireUniqueEmail = true
            };

            return manager;
        }
    }
}

UPDATED CODE: I ended up creating a class called UserEditViewModel and I'm also including the AppRole class which was in the sample project I'm tweaking.

   public class UserEditViewModel : IdentityUser
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string UserRole { get; set; }
            public IEnumerable<AppRole> AllRoles { get; set; }
        }

    public class AppRole : IdentityRole {

        public AppRole() : base() { }

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

Then in my controller I did the following. Keep in mind I'm only going to allow a user to be assigned to one role at a time so theoretically there should only be the one role which is why I only called on the userRoles[0]. Since I added the RoleManager after some sample users I have a couple users that aren't assigned to a Role. I added a check to make sure the Roles had a count and if not I display "User" as their role. I will go back and add code to actually add the user to the "User" role if no roles are found.

List<UserEditViewModel> UserList = new List<UserEditViewModel>();

            var users = UserManager.Users;
            foreach (AppUser user in users)
            {                    
                var userRoles = await UserManager.GetRolesAsync(user.Id);
                string roleName = userRoles.Count() == 0 ? "User" : userRoles[0];

                UserEditViewModel editUser = new UserEditViewModel();
                editUser.UserName = user.UserName;
                editUser.FirstName = user.FirstName;
                editUser.LastName = user.LastName;
                editUser.Email = user.Email;
                editUser.UserRole = roleName;
                editUser.AllRoles = RoleManager.Roles;
                UserList.Add(editUser);
            }

            return View(UserList);

Here is the View

<div class="form-group">
        <label>Role:</label> @Html.DisplayNameFor(model => model.UserRole)
    </div>

解决方案

I would look at ViewModels. It's generally bad practice to update an entity model in your view - especially security related entities. See https://www.stevefenton.co.uk/2013/03/Why-You-Never-Expose-Your-Domain-Model-As-Your-MVC-Model/

With a viewmodel, you could have a property for List<Role> that you populate in your controller and use in your view and another property like RoleId for the user's role.

In the POST you would do something like:

if (ModelState.IsValid)
{ 
    var roleMgr = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
    var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    var role = roleMgr.FindById(viewmodel.RoleId);
    if (role != null) userMgr.AddToRole(viewmodel.UserId, role.Name);
}

VIEW:

<div class="form-group">
    @Html.LabelFor(model => model.RoleId)
    <div class="col-md-2">
        @Html.DropDownListFor(model => model.RoleId, Model.RoleList, htmlAttributes: new { @class = "form-control" })
    </div>
    <div class="col-md-10 col-md-offset-2">
        @Html.ValidationMessageFor(model => model.RoleId, "", new { @class = "text-danger" })
    </div>
</div>

这篇关于需要关于如何获取/显示用户角色的理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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