簡體   English   中英

帶角色的用戶注冊

[英]User Registration with roles

我搜索了stackoverflow,但找不到我的問題的確切答案。

我有一個注冊頁面,我必須使用我已經在 AspNetRoles 中輸入的角色注冊用戶。 每當我運行代碼時,我都不明白問題出在哪里,它會給出錯誤 System.InvalidOperationException: Role xx does not exist。 帳戶視圖模型

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    public string Name { get; set; }
}

帳戶控制器

    // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        //ViewBag.Name = new SelectList(_context.Roles.ToList(), "Name", "Name");
        ViewBag.Name = _context.Roles.Select(b => new SelectListItem { Value = b.Name, Text = b.Name });
        return View();
    }

    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var UserPassword = model.Password;
            
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                Session.Add("UserName", user.Email);
                int role = 10;
                
                //Assign Role to user Here. Error is Here 
                await this.UserManager.AddToRoleAsync(user.Id, model.Name);
                //Ends Here

                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                return RedirectToAction("Index", "Home", new { user.Email, user.PasswordHash });
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

注冊.cshtml

@model ASPNetIdentity.Models.RegisterViewModel

    <!--Select the Role Type for the User.-->
    <div class="form-group">
        @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.Name, ViewBag.Name as SelectList, "--Select Role--", new { @class = "form-control" })
        </div>
    </div>
            <!--Ends Here-->                
           

但是錯誤頁面:在此處輸入圖片描述

需要幫助 問候

我不知道 AddToRoleSync 方法的內容,但在我看來,您應該從 Model.Name 屬性中獲取角色 id,然后您應該通過 id 值添加角色。

或者您可以創建 select 列表,id 為值,名稱為文本。

在我看來,您應該將所需的驗證添加到您的選擇列表中以強制分配角色。

我希望這個評論對你有用

您傳遞了錯誤的參數,如果您閱讀了文檔,這里說要傳遞 TUser https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.usermanager-1.addtoroleasync?view =aspnetcore-6.0

參數

user TUser 要添加到命名角色的用戶。

role String 要將用戶添加到的角色的名稱。 正確用法是:

var userResult = await this.UserManager.AddToRoleAsync(user, model.Name);

暫無
暫無

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

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