0
我想在我的ASP.NET MVC应用程序中创建超级用户。我读到,我可以通过添加"admin"
角色来实现它,并通过过滤器检查是当前用户是否具有此角色。实体框架,创建超级用户
我在教程中阅读了如何在应用程序启动时创建用户和角色,但是在所有教程中他们不使用实体框架。于是,我就在Configuration.cs
文件中Migration
文件夹中创建超级用户:
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");
}
}
}
}
但经过我添加的迁移和更新数据库中的新用户不会出现。我是否明白,每次迁移后Seed方法都会调用,并且应该创建一个新用户?如果是的话,我做错了什么?如果没有,当我的网络应用第一次启动时,我还可以添加超级用户吗?
您需要检查if( userAlreadyexists)return;我在这里没有发现任何错误..你有什么错误吗?我想你的管理员obejct没有要求所有字段(名字,姓氏)。请在Step7查看http://bitoftech.net/2015/03/11/asp-net-identity-2-1-roles-based-authorization-authentication-asp-net-web-api/ –