c# - 网站初始化时创建默认用户/管理员 - 身份

标签 c# asp.net asp.net-identity

我在 asp.net 领域非常菜鸟。所以我的问题可能在互联网上的任何地方都得到了回答,但我都不了解流创建。这是问题。

我正在尝试创建简单的“网站项目”,当该网站启动时,如果表尚不存在,它应该在数据库中创建所有必要的身份表。然后,我将向表中添加角色,并将一个用户设置为该表的 super 管理员。

任何人都可以帮助我解决这个问题或分享有关此问题的任何链接。

最佳答案

我假设您使用的是 ASP.NET MVC。

您可以使用 Database Initialization为您的数据库播种。

public class MyDBInitializer : CreateDatabaseIfNotExists<ApplicationDBContext>
{
    protected override void Seed(ApplicationDBContext context)
    {
        base.Seed(context);
    }
}

在种子方法上,您可以填充数据库并为您的应用程序创建默认用户。

protected override void Seed(ApplicationDBContext context)
{
    // Initialize default identity roles
    var store = new RoleStore<IdentityRole>(context);
    var manager = new RoleManager<IdentityRole>(store);               
    // RoleTypes is a class containing constant string values for different roles
    List<IdentityRole> identityRoles = new List<IdentityRole>();
    identityRoles.Add(new IdentityRole() { Name = RoleTypes.Admin });
    identityRoles.Add(new IdentityRole() { Name = RoleTypes.Secretary });
    identityRoles.Add(new IdentityRole() { Name = RoleTypes.User });

    foreach(IdentityRole role in identityRoles)
    {
         manager.Create(role);
    }

    // Initialize default user
    var store = new UserStore<ApplicationUser>(context);
    var manager = new UserManager<ApplicationUser>(store);
    ApplicationUser admin = new ApplicationUser();
    admin.Email = "admin@admin.com";
    admin.UserName = "admin@admin.com";

    manager.Create(admin, "1Admin!");
    manager.AddToRole(admin.Id, RoleTypes.Admin); 

    // Add code to initialize context tables

    base.Seed(context);
}

并且在您的 Global.asax.cs 上,您应该注册您的数据库初始化器

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    Database.SetInitializer(new MyDBInitializer());
}

请注意,有不同类型的数据库初始化策略,其行为取决于您的数据库初始化程序。请检查上面的链接。

关于c# - 网站初始化时创建默认用户/管理员 - 身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39737554/

相关文章:

c# - UseJwtBearerAuthentication 失败,IDX10504 : Unable to validate signature, token 没有签名

c# - Identity Owin 是否需要延迟加载?

c# - protobuf-net 线程安全吗?

c# - SQL 数据库中一对多关系的性能问题

c# - 通知编译器变量可能从另一个线程更新

c# - 使用 MapHttpRoute 配置 WebAPI 路由时出错

c# - Visual Studio 在 StackOverflowException 上丢失第一个堆栈帧

asp.net - Web API 和 SignalR Web 应用程序 - 身份验证和授权

c# - 异常记录中的空引用异常屏蔽真错误

c# - 如何创建属性以检查用户是否拥有 Identity core 2.2 的声明?