你的位置:首页 > ASP.net教程

[ASP.net教程]MVC5 Identity 自定义用户和角色


看代码基本就都能看懂了,增加了两个用户详细信息的表,角色表增加两个字段页面中实现树形显示。

//IdentityModels.csusing System.Data.Entity;using System.Security.Claims;using System.Threading.Tasks;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;namespace WebDemo20150801.Models{  public class ApplicationUser : IdentityUser  {    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)    {      var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);      return userIdentity;    }    public virtual UserSetting UsersSetting { get; set; }//增加两个表用来显示用户数据    public virtual UserInfo UsersInfo { get; set; }  }  public class UserSetting  {    public string Id { get; set; }    public string Theme { get; set; }  }  public class UserInfo  {    public string Id { get; set; }    public string TrueName { get; set; }    public string Phone { get; set; }  }  public class ApplicationRole : IdentityRole  {    public ApplicationRole() : base() { }    public ApplicationRole(string name) : base(name) { }    public ApplicationRole(string name, string description)      : this(name)    {      this.Description = description;    }    public string Description { get; set; }//角色表里新增加的字段    public string ParentRole { get; set; }  }  public class ApplicationDbContext : IdentityDbContext<ApplicationUser>  {    public ApplicationDbContext()      : base("DefaultConnection", throwIfV1Schema: false)    {    }    public new IDbSet<ApplicationRole> Roles { get; set; }//一定要重写这个方法,不然能用,网页中也能获取数据,就是代码里点不出来~~    public static ApplicationDbContext Create()    {      return new ApplicationDbContext();    }  }}

这是MVC5,MVC6看起来舒服多了,还能方便的修改ID为数字类型。 

public class IdentityDbContext : IdentityDbContext<IdentityUser, IdentityRole, string> { }

 但是现在的版本需要这样

  public class ApplicationDbContext     : IdentityDbContext<ApplicationUser, ApplicationRole,     string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>

 所以我放弃吧ID改成数字了。

这有ID变为数字的代码

https://github.com/TypecastException/AspNet-Identity-2-With-Integer-Keys/blob/master/IdentitySample/Models/IdentityModels.cs