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?
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With