簡體   English   中英

Asp Net MVC 角色安全

[英]Asp Net MVC Role Security

我在 asp net mvc 5 項目中遇到了角色。我可以在數據庫上創建角色類型,但無法將它們檢索到用戶注冊中,因為它在我的 Register.cshtml 上顯示錯誤“沒有類型為 '' 的 ViewData 項鍵 'Name' 誰能幫幫我嗎。 提前致謝。 這是我的控制器:

 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>

雖然我已經發布了另一種查找角色的方法,但是您的代碼我們很好,您是否在表中輸入了任何角色

AspNet角色

並在表中創建用戶和角色之間的關系

AspNet 用戶角色

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

    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中的protected override void Seed(RoleBasedSecurity.Models.ApplicationDbContext context)中寫入這些行

    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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM