为什么asp.net Identity用户id是字符串?

Ost*_*tap 17 c# asp.net database-design uniqueidentifier asp.net-identity-2

我想在asp.net web api应用程序中使用System.Guid类型作为我所有表的id.但我也使用Asp.net Identity,它使用字符串类型的id(也用于存储guid).所以我想知道为什么它默认使用字符串 id而不是System.Guid?什么是通过所有应用程序使用的更好的选择 - Guid id或string -guid id?在使用字符串的情况下 - 在代码或数据库中生成新id的最正确和最可靠的方法是什么?

Adr*_*ris 8

使用ASP.NET Core,您可以通过一种非常简单的方式为Identity的模型指定所需的数据类型.

第一步,将身份类从<string>覆盖到<您想要的数据类型>:

public class ApplicationUser : IdentityUser<Guid>
{
}

public class ApplicationRole : IdentityRole<Guid>
{
}
Run Code Online (Sandbox Code Playgroud)

使用您想要的类和数据类型声明数据库上下文:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }
    }
Run Code Online (Sandbox Code Playgroud)

在您的启动类中,使用模型声明身份服务并声明主键所需的数据类型:

services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext, Guid>()
            .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

  • 有关信息,现在官方文档中有一个主题:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-primary-key-configuration (2认同)

Tim*_*Tim 3

根据您使用的 ASP.Net 身份验证版本,数据库 ASP.NET Identity v2 应将其作为唯一标识符 (Guid) 存储在表中AspNetUsers。在更早的版本中,它将用户 ID 作为 int 存储在表中webpages_Membership

我相信它会将其显示为字符串,因此它可以是您喜欢的任何数据类型,然后可以根据需要在代码中进行转换。