【问题标题】:create user with more than one role in asp.net identity在 asp.net 身份中创建具有多个角色的用户
【发布时间】:2017-07-30 11:55:16
【问题描述】:

我正在尝试创建具有多个角色的用户这是我的新用户视图模型

 public class UserForNewViewModel
    {
        public RegisterViewModel User { get; set; }
        public List<IdentityRole> Roles { get; set; }
    }

这是我的行动

 [HttpGet]
    public async Task<ActionResult> Create()
    {
        var roles = await _context.Roles.ToListAsync();
        var model = new UserForNewViewModel()
        {
            Roles = roles
        };
        return View(model);
    }

考虑到我如何处理多个角色

<div class="form-group">
            <label>Roles</label>
            ???????????????????????????????????
            @Html.DropDownListFor(x => x.Roles., new SelectList(Model.Roles, "Id", "Name"), ("Seçin..."), new { @class = "form-control", id = "ParentId" })
        </div>

【问题讨论】:

    标签: c# asp.net-mvc asp.net-identity role


    【解决方案1】:

    例如,您可以使用复选框来做到这一点

     <div class="col-md-10">
                @foreach (var item in (SelectList)ViewBag.RoleId)
                {
                    <input type="checkbox" name="SelectedRoles"
                           value="@item.Value" class="checkbox-inline" />
                    @Html.Label(item.Value, new { @class = "control-label" })
                }
            </div>
    

    【讨论】:

      【解决方案2】:

      我需要在用户创建阶段为特定用户添加多个用户角色。

      所以我要在前端使用复选框来实现这一点

      所以这是视图页

      @model project_name.Models.RegisterViewModel
      
      @{
      
      }
      
      @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal"}))
      {
      
              <div class="form-group">
                  <label class="col-md-2 control-label">
                      Select User Role
                  </label>
                  <div class="col-md-10">
                      @foreach (var item in (SelectList)ViewBag.RoleId)
                      {
                          <input type="checkbox" name="SelectedRoles"
                                 value="@item.Value" class="checkbox-inline" />
                          @Html.Label(item.Value, new { @class = "control-label" })
                      }
                  </div>
              </div>
      
                  ....
      
                  <div class="form-group">
                      <div class="col-md-offset-2 col-md-10">
                          <input type="submit" class="btn btn-default" value="Register" />
                      </div>
                  </div>
      }
      

      这些是我对 App_Start 文件夹中现有的 AspNet Identity 2.0 framework 所做的更改 => IdentityConfig.cs 文件

          public class RoleManager<TRole> : RoleManager<TRole, string> where TRole : class, IRole<string>
          {
              //
              // Summary:
              //     Constructor
              //
              // Parameters:
              //   store:
              public RoleManager(IRoleStore<TRole, string> store);
          }
      
             public class ApplicationRoleManager : RoleManager<ApplicationRole>
              {
                  public ApplicationRoleManager(
                      IRoleStore<ApplicationRole, string> roleStore)
                      : base(roleStore)
                  {
                  }
                  public static ApplicationRoleManager Create(
                      IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
                  {
                      return new ApplicationRoleManager(
                          new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
                  }
           }
      

      这些是我对 Models 文件夹中现有的 AspNet Identity 2.0 framework 所做的更改 => IdentityModels.cs 文件

          public class ApplicationUser : IdentityUser
      {
          public async Task<ClaimsIdentity> GenerateUserIdentityAsync(
              UserManager<ApplicationUser> manager)
          {
              var userIdentity = await manager.CreateIdentityAsync(
                  this, DefaultAuthenticationTypes.ApplicationCookie);
              return userIdentity;
          }
      }
      
         public class ApplicationRole : IdentityRole
          {
              public ApplicationRole() : base() { }
              public ApplicationRole(string name) : base(name) { }
              public string Description { get; set; }
          }
      

      那么我设置了控制器的注册方法如下

         // POST: /Account/Register
          [HttpPost]
          [AllowAnonymous]
          [ValidateAntiForgeryToken]
          public async Task<ActionResult> Register(RegisterViewModel model, HttpPostedFileBase upload, params string[] selectedRoles)
          {
      
              try
              {
                  if (ModelState.IsValid)
                  {
                      var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };                      
      
      
                      var result = await UserManager.CreateAsync(user, model.Password);
      
                      if (result.Succeeded)
                      {
                          //Add User to the selected Roles 
                          if (selectedRoles != null)
                          {
                              var addroles = await UserManager.AddToRolesAsync(user.Id, selectedRoles);
                              if (!addroles.Succeeded)
                              {
                                  ModelState.AddModelError("", result.Errors.First());
                                  ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync("Name", "Name"));
                                  return View();
                              }
                          }
      
                      }
      
                      else
                      {
                          ModelState.AddModelError("", result.Errors.First());
                          ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
                          return View();
                      }
      
                      return RedirectToAction("Index");
                      // AddErrors(result);
                  }
      
              }
      
              // If we got this far, something failed, redisplay form
              catch (RetryLimitExceededException /* dex */)
              {
                  //Log the error (uncomment dex variable name and add a line here to write a log.
                  ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
              }
      
              ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
      
              return View(model);
          }
      

      但上述控制器的每一行存在“RoleManager”字我得到编译时错误如下

      使用泛型'RoleManager TRole, TKey'需要2个类型 论据

      这意味着我在上述方法中遇到了 3 个编译时错误。

      我也跟着this reference 获得了在 aspnet 身份中为用户分配多个角色的想法


      编辑:

      我刚刚改了IdentityRole.cs[MetaData]IdentityUserRole[MetaData]也如下

      namespace Microsoft.AspNet.Identity.EntityFramework
      {
          //
          // Summary:
          //     Represents a Role entity
      
          public class IdentityRole : IdentityRole<string, IdentityUserRole>
          {
              //
              // Summary:
              //     Constructor
              public IdentityRole();
              //
              // Summary:
              //     Constructor
              //
              // Parameters:
              //   roleName:
              public IdentityRole(string roleName);
          }   
      
      public class IdentityRole<TKey, TUserRole> : IRole<TKey>
      where TUserRole : IdentityUserRole<TKey>
      {
          public TKey Id
          {
              get
              {
                  return JustDecompileGenerated_get_Id();
              }
              set
              {
                  JustDecompileGenerated_set_Id(value);
              }
          }
          public string Name
          {
              get;
              set;
          }
          public ICollection<TUserRole> Users
          {
              get
              {
                  return JustDecompileGenerated_get_Users();
              }
              set
              {
                  JustDecompileGenerated_set_Users(value);
              }
          }
          public IdentityRole()
          {
              this.Users = new List<TUserRole>();
          }
      }
      
      public class IdentityUserRole<TKey>
      {
          public virtual TKey RoleId
          {
              get;
              set;
          }
          public virtual TKey UserId
          {
              get;
              set;
          }
          public IdentityUserRole()
          {
          }
      }
      }
      

      【讨论】:

      • 另一种选择是在您发布时使用单个授权过滤器,但删除内部引号。 [授权(角色=“成员,管理员”)]
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-05
      • 2017-11-03
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 2015-09-17
      • 2016-09-05
      相关资源
      最近更新 更多