Setting role when creating new user with ASP.net MVC

Maestro1024 picture Maestro1024 · Mar 31, 2011 · Viewed 11.7k times · Source

Setting role when creating new user with ASP.net MVC

I am looking at the default ASP.net MVC 2 controller.

How do I set the role for the new user that is created in the Register method?

Is this possible with just a simple property set or do I have to do something special?

Answer

anthonyvscode picture anthonyvscode · Mar 31, 2011

Just add the second line below into your AccountController:

if (createStatus == MembershipCreateStatus.Success)
{
    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
    Roles.AddUserToRole(model.UserName, "RoleNameHere");
    return RedirectToAction("Index", "Home");
}

EDIT: If you haven't created the Role already (you only need to do it once.), it will cause an exception.

Just put the code below above the AddUserToRole Method.

    if (!Roles.RoleExists("RoleNameHere"))
        Roles.CreateRole("RoleNameHere")