Seeding data and creating/managing roles in MVC4 - how hard can it be?

a 夏天 提交于 2019-12-01 09:37:30

Finally, I managed to make the whole thing work!

My seed method now looks like this:

WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

if (!Roles.RoleExists("Admins"))
{
    Roles.CreateRole("Admins");
}
if (!WebSecurity.UserExists("admin"))
{
    WebSecurity.CreateUserAndAccount("admin", "123456");
}
if (!Roles.GetRolesForUser("admin").Contains("Admins"))
{
    Roles.AddUsersToRoles(new[] { "admin" }, new[] { "Admins" });
}
base.Seed(context);

My App_Start in Global.asax looks like this:

Database.SetInitializer(new DataContextDbInitializer());
DataContext c = new DataContext();
c.Database.Initialize(true);

I'm not sure if this is actually doing something, but I have this inside the the system.web tag in Web.config:

<roleManager enabled="true" cacheRolesInCookie="true" />

I also removed [InitializeSimpleMembership] from AccountController, and the UsersContext class in AccountModels. I moved this bit to my own context class:

public DbSet<UserProfile> UserProfiles { get; set; }

Then, to test if everything works, I use the [Authorize(Roles = "Admins")] annotation on top of the About() method in the HomeController. If things are working as expected, this should force me to log in as admin/123456 in order to be able to see the "About" page, controlled by HomeController/About. Which does ;)

Thanks for the help! It contributed to me understanding a bit more what was going on.

Dennis Bottjer

In MVC4 a default Internet Application has Authentication built-in. A class called InitializeSimpleMembershipAttribute is located in a Filters directory. As the name suggests this class Initializes the Simple Membership Database. If you look at the constructor you'll see the following line:

 WebSecurity.InitializeDatabaseConnection("UserContext", "UserProfile", "UserId", "UserName", autoCreateTables: true);

Below this line you can insert the following code to create a default user:

// Create admin user.
                    if (!WebSecurity.UserExists("admin"))
                    {
                        WebSecurity.CreateUserAndAccount("admin", "12345678!");
                    }

Just another way to do things.

Try like this:

public class DataContextDbInitializer : DropCreateDatabaseAlways<DataContext>
{
    protected override void Seed(DataContext context)
    {
        if (!Roles.RoleExists("Admins"))
        {
            Roles.CreateRole("Admins");
        }
        if (!WebSecurity.UserExists("admin"))
        {
            WebSecurity.CreateUserAndAccount("admin", "123456");
        }
        if (!Roles.GetRolesForUser("admin").Contains("Admins"))
        {
            Roles.AddUsersToRoles(new[] { "admin" }, new[] { "Admins" });
        }
    }
}

and in your Application_Start:

Database.SetInitializer<DataContext>(new DataContextDbInitializer());
using (var ctx = new DataContext())
{
    ctx.Database.Initialize(true);
}
WebSecurity.InitializeDatabaseConnection(
    "DefaultConnection", 
    "UserProfile", 
    "UserId", 
    "UserName", 
    autoCreateTables: true
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!