Tuesday, March 18, 2014

You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class

In the Account Controller Register action (public ActionResult Register(RegisterModel model)) I have a code below that by default assign a Customer Role to a new user during registration. In my database, the defined roles are "Administrator" and "Customer". However, the code below generates exception as stated on the title post.
Code:
SimpleRoleProvider role = new SimpleRoleProvider();
role.AddUsersToRoles(new string[] { model.UserName }, new string[] { "Customer" });
The solution would be to use the Role class defined in System.Web.Security namespace instead of SimpleRoleProvider:
Code:
Roles.AddUserToRole(model.UserName, "Customer");

Reference: Perils of MVC 4 AccountController
Cheers! :)

0 comments:

Post a Comment