How do I add first user (root) in ASP.NET MVC app?

2019-08-01 06:05发布

问题:

I'm using ASP.NET MVC Framwork and trying to grok the ASP Membership 3.5 stuff.

What is the best way to add the first administrator user without having to log in? I've been staring at the membership starter kit's source without finding it.

回答1:

A simple solution (especially or rather only for dev. purposes) by doing it in a "setup" action:

if (!Roles.RoleExists("Administrator"))
{
    Roles.CreateRole("Administrator");
}
if (Membership.GetUser("Admin") == null)
{
    Membership.CreateUser("Admin", "Admin");
    Roles.AddUserToRole("Admin", "Administrator");
}


回答2:

Depends on what memebership provider your are using.. If your using a SQL memembershipprovider you should be able to use the regular Asp.Net Configuration tool. (Project menu -> Asp.Net Configuration)



回答3:

You said you were going to share the project. I would recommend creating a one-time-run page that creates the user and assigns it the roel you want. After that any concurrent runs of the page should than check for the user you want and if it exists to redirect away or some other mechanic.