注册用户时设置AspNetUserRoles

问题描述 投票:0回答:2

这是我想做的:我想在注册页面上将AspNetUserRole设置为新用户。

型号:

    namespace MyProject.Models
    {
        public enum AccountRole
        {
            Responder = 10003, Sender= 10002, Admin = 10001
        }

        ...

        [Required()]
        [Display(Name = "Account role")]
        public AccountRole? AccountRole { get; set; }

视图:

@Html.LabelFor(model => model.AccountRole, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EnumDropDownListFor(model => model.AccountRole, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.AccountRole, "", new { @class = "text-danger" })
        </div>

注册页面结果: http://imgur.com/1lHL06L

Controller:

    // 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 };
            IdentityResult result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                //User accountRole to AspNetUserRoles BY JULIUS
                var accountRole = model.AccountRole;

                await SignInAsync(user, isPersistent: false);

                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                var callbackUrl = Url.Action("ConfirmEmail", "Account",
                   new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(user.Id,
                   "Confirm your account", "Please confirm your account by clicking <a href=\""
                   + callbackUrl + "\">here</a>");


                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }

请把注意力转移到AccountController.cs注册部分。我已经成功从下拉列表中收集了输入的AccountRole枚举

var accountRole = model.AccountRole;

我要在实体框架中生成的[[DefaultConnection

中将accountRole设置为AspNetUserRoles

表格:

http://i.imgur.com/YBI3NSp.png
我该如何在我的控制器代码中解决这个问题?

这是我想做的:我想在注册页面上将AspNetUserRole设置为新用户。型号:命名空间MyProject.Models {公共枚举AccountRole {...

c# asp.net-mvc registration account role
2个回答
4
投票
据我了解,您可能想扩展IdentityUserRole类。此类表示用户与其角色之间的关系。

0
投票
我来晚了,但是今天对我有帮助:
© www.soinside.com 2019 - 2024. All rights reserved.