Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting role when creating new user with ASP.net MVC

Tags:

asp.net

roles

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?

like image 477
Maestro1024 Avatar asked Mar 31 '11 00:03

Maestro1024


1 Answers

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")
like image 51
anthonyvscode Avatar answered Oct 27 '22 00:10

anthonyvscode