在asp mvc身份中添加数据库中的角色

时间:2016-10-17 16:54:29

标签: asp.net-mvc asp.net-identity identity asp.net-identity-2

我需要在用户注册表添加表格AspNetRole时添加用户ID和角色ID。

但是当我创建用户时会显示此错误。

enter image description here

如何在数据库中插入角色?

/ ********************************************** ************************************************** * /

identityconfig:

 public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
        : base(roleStore)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
    }
}

public static class SecurityRole
    {
        public const string Admin = "admin";
        public const string Accounting = "accounting";
    }

StartupAuth:

app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

AccountController:

public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

    public async Task<ActionResult> Register(RegisterViewModel model, HttpPostedFileBase IamgeProfile)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Username, Email = model.Email };
            user.Name = model.Name;
            user.Family = model.Family;
            user.Address = model.Address;
            user.BankName = model.BankName;
            user.City = model.City;
            user.Ostan = model.Ostan;
            user.PhoneNumber = model.PhoneNumber;
            user.HomeNumber = model.HomeNumber;
            user.ShabaNo = model.ShabaNo;
            user.PostaCode = model.PostaCode;
            user.NationalCode = model.NationalCode;
            if (IamgeProfile != null)
            {
                IamgeProfile = Request.Files[0];
                var ext = System.IO.Path.GetExtension(IamgeProfile.FileName);
                if (ext == ".jpeg" || ext == ".jpg" || ext == ".png")
                {
                    string filename = model.Name + model.Family + model.NationalCode + ext;
                    IamgeProfile.SaveAs(Server.MapPath(@"~/Images/UserImageProfile/" + filename));
                    user.IamgeProfile = filename;
                }
            }
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                await UserManager.AddToRoleAsync(user.Id, role: SecurityRole.Accounting);
                var 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 this link: <a href=\"" + callbackUrl + "\">link</a>");
                ViewBag.Link = callbackUrl;
                return View("DisplayEmail");
            }
            AddErrors(result);
        }

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

1 个答案:

答案 0 :(得分:2)

要在AspNetRoles中添加角色,您可以在Seed()或其他启动方法中执行此操作:

<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div ng-app="ChartApp" ng-controller="ChartCtrl">
     <pre style="width: 30%; height: 10pc; overflow-y: scroll; float:left;">
       {{logItems | json}} 
    </pre>
    <div id="chart_div" style="float:left; width:60%; height: 180px;"></div>
</div>

https://msdn.microsoft.com/en-us/library/dn613057(v=vs.108).aspx