当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Entity Framework, create superuser

问题描述:

I want to create superuser in my ASP.NET MVC application. I read that I can achieve it by adding "admin" role and check by filters is a current user has this role.

I read in tutorials how to create users and roles when app start, but in all tutorials they don't use entity framework. So I tried to create superuser in Configuration.cs file in the Migration folder:

namespace WebApp.Migrations

{

using Microsoft.AspNet.Identity;

using Microsoft.AspNet.Identity.EntityFramework;

using System;

using System.Data.Entity;

using System.Data.Entity.Migrations;

using System.Linq;

using WebApp.Models;

internal sealed class Configuration : DbMigrationsConfiguration<WebApp.Models.ApplicationDbContext>

{

protected override void Seed(WebApp.Models.ApplicationDbContext context)

{

var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

roleManager.Create(new IdentityRole { Name = "admin" });

var admin = new ApplicationUser { Email = "[email protected]", UserName = "Growapps" };

string password = "mail123";

var result = userManager.Create(admin, password);

if (result.Succeeded)

{

userManager.AddToRole(admin.Id, "admin");

}

}

}

}

But after I add-migrations and update-database new user doesn't appear. Am I understand right, that Seed method calls after each migration and should create a new user? If yes, what am I doing wrong? If not, how else can I add super user when my web app first start?

网友答案:

So the mistake was not obvious, in "log in" view of template (that is generated by ASP.NET MVC) u should type "email" and password, the problem is that Login method in controller sends that email field as user name, so if u create user in code with different values of name and email u will have difficulty to log in. I guess microsoft should change placeholder name of field in their template :D

分享给朋友:
您可能感兴趣的文章:
随机阅读: