我正在使用Identity 1.0实体框架Web应用程序开发MVC5。在我的种子方法中,我尝试在第一次迁移期间为我的用户分配角色。我在输入时出现错误
Role = "Admin"
属性或索引器"标识用户应用程序用户登录,应用程序用户角色,应用程序用户声明>。角色不能分配给 - 它是只读的
这是否意味着在运行应用程序时必须在网站上手动分配角色?
配置.cs
var roles = new List<ApplicationRole>
{
new ApplicationRole { Id = 1, Name = "Admin"},
new ApplicationRole { Id = 2, Name = "User"},
};
roles.ForEach(s => context.Roles.AddOrUpdate(p => p.Name, s));
context.SaveChanges();
var passwordHash = new PasswordHasher();
string password = passwordHash.HashPassword("Password@123");
var users = new List<ApplicationUser>
{
new ApplicationUser { UserName = "jackie@hotmail.com", FirstMidName = "Jackie", LastName = "Chan", Email="jasonw@rs.kiwi.nz",PasswordHash = password, Roles = "Admin",
EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1,DepotID = 1,IsAdministrator = true,SecurityStamp = Guid.NewGuid().ToString()},
users.ForEach(s => context.Users.AddOrUpdate(p => p.UserName, s));
context.SaveChanges();
身份模型.cs
namespace RecreationalServicesTicketingSystem.Models
{
public class ApplicationUserLogin : IdentityUserLogin<int> { }
public class ApplicationUserClaim : IdentityUserClaim<int> { }
public class ApplicationUserRole : IdentityUserRole<int> { }
public class ApplicationRole : IdentityRole<int, ApplicationUserRole>, IRole<int>
{
public string Description { get; set; }
public ApplicationRole() : base() { }
public ApplicationRole(string name)
: this()
{
this.Name = name;
}
public ApplicationRole(string name, string description)
: this(name)
{
this.Description = description;
}
}
public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
var userIdentity = await manager
.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public bool IsAdministrator { get; set; }
[StringLength(50, MinimumLength = 1)]
public string LastName { get; set; }
[StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")]
[Column("FirstName")]
public string FirstMidName { get; set; }
public string FullName
{
get { return FirstMidName + " " + LastName; }
}
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department { get; set; }
public int DepotID { get; set; }
[ForeignKey("DepotID")]
public virtual Depot Depot { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
public class ApplicationDbContext
: IdentityDbContext<ApplicationUser, ApplicationRole, int,
ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
static ApplicationDbContext()
{
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public DbSet<Ticket> Tickets { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Depot> Depots { get; set; }
}
public class ApplicationUserStore :
UserStore<ApplicationUser, ApplicationRole, int,
ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUserStore<ApplicationUser, int>, IDisposable
{
public ApplicationUserStore()
: this(new IdentityDbContext())
{
base.DisposeContext = true;
}
public ApplicationUserStore(DbContext context)
: base(context)
{
}
}
public class ApplicationRoleStore
: RoleStore<ApplicationRole, int, ApplicationUserRole>,
IQueryableRoleStore<ApplicationRole, int>,
IRoleStore<ApplicationRole, int>, IDisposable
{
public ApplicationRoleStore()
: base(new IdentityDbContext())
{
base.DisposeContext = true;
}
public ApplicationRoleStore(DbContext context)
: base(context)
{
}
}
}
角色控制器
namespace RecreationalServicesTicketingSystem.Controllers
{
//[Authorize(Roles = "Admin")]
public class RolesAdminController : Controller
{
public RolesAdminController()
{
}
public RolesAdminController(ApplicationUserManager userManager,
ApplicationRoleManager roleManager)
{
UserManager = userManager;
RoleManager = roleManager;
}
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
set
{
_userManager = value;
}
}
private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
//
// GET: /Roles/
public ActionResult Index()
{
return View(RoleManager.Roles);
}
//
// GET: /Roles/Details/5
public async Task<ActionResult> Details(int id)
{
if (id > 0)
{
var role = await RoleManager.FindByIdAsync(id);
// Get the list of Users in this Role
var users = new List<ApplicationUser>();
// Get the list of Users in this Role
foreach (var user in UserManager.Users.ToList())
{
if (await UserManager.IsInRoleAsync(user.Id, role.Name))
{
users.Add(user);
}
}
ViewBag.Users = users;
ViewBag.UserCount = users.Count();
return View(role);
}
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//
// GET: /Roles/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Roles/Create
[HttpPost]
public async Task<ActionResult> Create(RoleViewModel roleViewModel)
{
if (ModelState.IsValid)
{
// Use ApplicationRole, not IdentityRole:
var role = new ApplicationRole(roleViewModel.Name);
var roleresult = await RoleManager.CreateAsync(role);
if (!roleresult.Succeeded)
{
ModelState.AddModelError("", roleresult.Errors.First());
return View();
}
return RedirectToAction("Index");
}
return View();
}
//
// GET: /Roles/Edit/Admin
public async Task<ActionResult> Edit(int id)
{
if (id > 0)
{
var role = await RoleManager.FindByIdAsync(id);
if (role == null)
{
return HttpNotFound();
}
RoleViewModel roleModel = new RoleViewModel { Id = role.Id, Name = role.Name };
return View(roleModel);
}
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//
// POST: /Roles/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Name,Id")] RoleViewModel roleModel)
{
if (ModelState.IsValid)
{
var role = await RoleManager.FindByIdAsync(roleModel.Id);
role.Name = roleModel.Name;
await RoleManager.UpdateAsync(role);
return RedirectToAction("Index");
}
return View();
}
//
// GET: /Roles/Delete/5
public async Task<ActionResult> Delete(int id)
{
if (id > 0)
{
var role = await RoleManager.FindByIdAsync(id);
if (role == null)
{
return HttpNotFound();
}
return View(role);
}
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//
// POST: /Roles/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id, string deleteUser)
{
if (ModelState.IsValid)
{
if (id > 0)
{
var role = await RoleManager.FindByIdAsync(id);
if (role == null)
{
return HttpNotFound();
}
IdentityResult result;
if (deleteUser != null)
{
result = await RoleManager.DeleteAsync(role);
}
else
{
result = await RoleManager.DeleteAsync(role);
}
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
return View();
}
return RedirectToAction("Index");
}
else
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
}
return View();
}
}
}
新 ApplicationUser 对象的 roles 属性需要 applicationUserRole 项的 iCollection。请参阅下面的示例。
new ApplicationUser
{
UserName = "jackie@hotmail.com",
FirstMidName = "Jackie",
LastName = "Chan",
Email = "jasonw@rs.kiwi.nz",
PasswordHash = password,
Roles =
{
new ApplicationUserRole
{
RoleId = 1
}
},
EnrollmentDate = DateTime.Parse("2016-02-18"),
DepartmentID = 1,
DepotID = 1,
IsAdministrator = true,
SecurityStamp = Guid.NewGuid().ToString()
}