首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用ASP.NET标识创建默认用户帐户

使用ASP.NET标识创建默认用户帐户
EN

Stack Overflow用户
提问于 2013-10-27 14:53:08
回答 2查看 9.7K关注 0票数 3

我正在使用ASP.NET MVC5和Identity API开发一个简单的应用程序。我想问一下,在创建表和启动应用程序时,如何在超级管理员角色中创建超级管理员帐户。我正在使用Visual Studio2013的默认ASP.NET MVC5 with Accounts模板,但我不确定如何实现我的目标。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-27 15:00:22

不要紧,我找到了这个有用的链接,它准确地显示了我想要的内容:

https://github.com/rustd/AspnetIdentitySample/blob/master/AspnetIdentitySample/App_Start/IdentityConfig.cs

票数 5
EN

Stack Overflow用户

发布于 2016-07-21 23:34:20

我在Configuration类的seed()方法中这样做:

代码语言:javascript
运行
复制
protected override void Seed(AuthContext context)
{
    const string userName = "AdminUserName";
    const string password = "AdminPassword";
    const string roleName = "AdminRole";
    const string phoneNumber = "PhoneNumber";

    var appUserStore = new UserStore<ApplicationUser>(context);
    var appUserManager = new UserManager<ApplicationUser>(appUserStore);
    var appRoleManager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context));

    try
    {
        var user = context.Users.SingleOrDefault(u => u.UserName == userName);
        var role = context.Roles.SingleOrDefault(r => r.Name == roleName);

        if (role == null)
        {
            appRoleManager.CreateAsync(new IdentityRole(roleName)).Wait();
            role = context.Roles.SingleOrDefault(r => r.Name == roleName);
        }
        if (user == null)
        {
            appUserManager.CreateAsync(new ApplicationUser { UserName = userName, PhoneNumber = phoneNumber}, password).Wait();
            user = context.Users.SingleOrDefault(u => u.UserName == nationalCode);
        }

        var userRole = user.Roles.SingleOrDefault(r => r.RoleId == role.Id);

        if (userRole == null)
        {
            appUserManager.AddToRoleAsync(user.Id, roleName).Wait();
        }
    }
    catch (Exception ex)
    {
        // Error catched!
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19615441

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档