如何为在ASP.NET MVC中创建的第一个帐户设置角色?

时间:2017-05-02 23:15:06

标签: c# asp.net asp.net-mvc asp.net-mvc-4

根据我的理解,当用户在ASP.NET MVC中创建新帐户时,处理此问题的方法将是位于任何MVC解决方案的AccountController类中的Register方法。这是我班级当前方法的样子:

// GET: /Account/Register
[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 };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

            // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
            // Send an email with this link
            // 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");
        }
        AddErrors(result);
    }

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

然而,从我注意到的是,没有关于处理角色的代码。我的目标是为要创建的第一个用户设置角色并使其成为Admin角色。之后要注册的所有用户都应该与该角色不同。我怎么能在这段代码中解决这个问题?

修改:我是否必须使用Seed Migrations\Configuration.cs方法才能实现此目的?如果是这样,我的Seed方法应该怎么样?

1 个答案:

答案 0 :(得分:2)

是的,您可以使用seed方法初始化rolesadmin user。 例如:

    protected override void Seed(ApplicationDbContext context)
     {
//initialized Role
       context.Roles.AddOrUpdate(r => r.Name,
                    new IdentityRole { Name = "SuperAdmin" },
                    new IdentityRole { Name = "Admin" },  
                    new IdentityRole { Name = "User" }
                    );

    //initialized Admin user
    if (!context.Users.Any(u => u.UserName == "ashiquzzaman@outlook.com"))
                {
                    var store = new UserStore<ApplicationUser>(context);
                    var manager = new UserManager<ApplicationUser>(store);
                    var user = new ApplicationUser
                    {                 
                        UserName = "ashiquzzaman@outlook.com",
                        Email = "ashiquzzaman@outlook.com",
                        PhoneNumber = "+8801717252600",                  
                        //.......
                    };
                    manager.Create(user, "aSHIQ!109");
                    manager.AddToRole(user.Id, "Admin");
                }
      }