在ASP.NET Identity中向AspNetUserClaims添加列

Tro*_*sen 1 c# asp.net entity-framework asp.net-identity

Microsoft.AspNet.Identity.Core 2.2.1在解决方案中使用。我需要将此与另一个应自动添加声明的系统集成。

为了跟踪哪些索偿是手动添加的,哪些索偿是由外部系统创建的,我想在AspNetUserClaims表格中添加另一列:

ExternalSystem varchar(64) null
Run Code Online (Sandbox Code Playgroud)

鉴于我的解决方案中实际上没有Claims类,我该如何使用EF迁移(或在没有必要时不使用)进行此操作?

Edi*_*vić 5

您可以创建自己的自定义应用程序用户声明类,该类派生自IdentityUserClaim类,并添加自定义字段。

public class ApplicationUserClaim : IdentityUserClaim
{
    public ApplicationUserClaim() { }

    public ApplicationUserClaim(string userId, string claimType,
        string claimValue, string externalSystem)
    {
        UserId = userId;
        ClaimType = claimType;
        ClaimValue = claimValue;
        ExternalSystem = externalSystem;
    }

    [MaxLength(64)]
    public string ExternalSystem { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

之后,您需要配置ApplicationDbContext和ApplicationUser类,例如:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole, string,
        IdentityUserLogin, IdentityUserRole, ApplicationUserClaim>
{
    // ...
}

public class ApplicationUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, ApplicationUserClaim>
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

此外,您必须创建自定义UserStore类,例如:

public class ApplicationUserStore : UserStore<ApplicationUser, IdentityRole, string,
        IdentityUserLogin, IdentityUserRole, ApplicationUserClaim>
{
    public ApplicationUserStore(ApplicationDbContext context)
        : base(context)
    {
    }
} 
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样使用ApplicationUserManager:

var ctx = new ApplicationDbContext();
var manager = new ApplicationUserManager(new ApplicationUserStore(ctx));
Run Code Online (Sandbox Code Playgroud)