Asp Net MVC角色安全

时间:2016-04-07 15:05:49

标签: c# asp.net-mvc asp.net-identity user-roles

我在我的asp net mvc 5项目中遇到了角色。我可以在数据库上创建角色类型,但不能将它们重新转换为用户注册,因为它在我的Register.cshtml上显示错误"有没有类型''的ViewData项目有关键'名称" 。谁能帮帮我吗。 提前致谢。 这是我的控制器:

 private ApplicationSignInManager _signInManager;
            private ApplicationUserManager _userManager;
            ApplicationDbContext context;
            public AccountController()
            {       

            }

            public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
            {
                UserManager = userManager;
                SignInManager = signInManager;
                context = new ApplicationDbContext();
            }

我的注册行动

 [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await this.UserManager.AddToRoleAsync(user.Id, model.Name);
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }
            // If we got this far, something failed, redisplay form

            return View(model);
        }

我的观点

<div class="form-group">
            @Html.Label("Select Your User Type", new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.DropDownList("Name")

            </div>

1 个答案:

答案 0 :(得分:0)

虽然我已经发布了另一种方法来查找角色,但您的代码很好,您在表格中输入了任何角色

  

AspNetRoles

并在表

中创建了用户和角色之间的关系
  

AspNetUserRoles

要查找特定用户的所有角色,您可以使用以下代码

    RoleBasedSecurity.Models.ApplicationDbContext context = new ApplicationDbContext();
    ApplicationUser au = context.Users.First(u => u.UserName == "admin@admin.com");

    foreach (IdentityUserRole role in au.Roles)
    {
        string name = role.RoleId;
        string RoleName = context.Roles.First(r => r.Id == role.RoleId).Name;
    }

创建角色的代码在 cofiguration.cs

中的 protected override void Seed(RoleBasedSecurity.Models.ApplicationDbContext context)中写下这些行
    if (!context.Roles.Any(r => r.Name == "User"))
    {
        var store = new RoleStore<IdentityRole>(context);
        var manager = new RoleManager<IdentityRole>(store);
        var role = new IdentityRole { Name = "User" };

        manager.Create(role);
    }

将用户附加到角色的代码在 cofiguration.cs

中的受保护覆盖​​void Seed(RoleBasedSecurity.Models.ApplicationDbContext上下文)中写下这些行
    if (!context.Users.Any(u => u.UserName == "admin@admin.com"))
    {
        var store = new UserStore<ApplicationUser>(context);
        var manager = new UserManager<ApplicationUser>(store);
        var user = new ApplicationUser { UserName = "admin@admin.com", Email = "admin@admin.com" };
        manager.Create(user, "password");
        manager.AddToRole(user.Id, "Admin");
    }

要为特定用户带来角色,您必须编写此代码。

ApplicationUser user = UserManager.FindByName(model.UserName);
string userId = user != null ? user.Id : null;
var roles = userId != null ? UserManager.GetRoles(userId) : null;
if (roles != null)
{
    foreach (var item in roles)
    {
        //Assign user roles
        UserManager.AddToRole(userId, item);
    }
}

并获得所有角色执行此操作

    ApplicationDbContext context = new ApplicationDbContext();
    var roles = context.Roles;