Ram*_*ppy 5 asp.net-mvc-5 asp.net-identity
我正在使用ASPNet Identity在我的Web应用程序中实现安全性.
有一个要求,我需要扩展IdentityRole和IdentityUser.
这是扩展IdentityUser的代码.
public class ApplicationUser : IdentityUser
{
public virtual User User { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("name=CoreContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>()
.ToTable("AspNetUsers");
modelBuilder.Entity<ApplicationUser>()
.ToTable("AspNetUsers");
}
}
Run Code Online (Sandbox Code Playgroud)
我唯一的问题是IdentityRole
要扩展用户,请更新您的ApplicationUser班级(位于IdentityModels.cs)
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager
.CreateIdentityAsync(this,
DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
// Use a sensible display name for views:
[Display(Name = "Postal Code")]
public string PostalCode { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
要扩展角色,请创建一个类 ApplicationRole.cs
public class ApplicationRole : IdentityRole
{
public ApplicationRole() : base() { }
public ApplicationRole(string name) : base(name) { }
public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
并在IdentityConfig.cs文件中添加类:
public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
public ApplicationRoleManager(
IRoleStore<ApplicationRole,string> roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(
IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(
new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
}
}
Run Code Online (Sandbox Code Playgroud)
现在清除旧数据库,运行应用程序并注册用户.它将在AspNetUsers表中创建另外3个字段(Address,City,State),并在AspNetRoles表中再创建一个字段(Description).而已.
有关详细信息,请转到以下站点: 扩展身份角色
小智 4
您可以像继承 IdentityUser 一样从应用程序中继承 IdentityRole。为什么需要扩展 IdentityRole?请查看以下文章,其中详细解释了您要执行的操作http://typecastexception.com/post/2014/02/13/ASPNET-MVC-5-Identity-Extending-and-Modifying-Roles。 ASPX
| 归档时间: |
|
| 查看次数: |
9642 次 |
| 最近记录: |