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

29

我想在ASP.NET Web API应用程序的所有表中使用 System.Guid 类型作为标识。但是,我还使用Asp.net Identity,它使用字符串类型的标识(也可以存储GUID)。所以,我想知道为什么默认情况下使用字符串 ID,而不是System.Guid?在整个应用程序中使用Guid ID还是字符串-GUID ID更好?如果使用字符串,生成新ID的最适当和可靠的方式是在代码中还是在数据库中?


1
这里解释了“为什么”(https://dev59.com/hGIk5IYBdhLWcg3we-H5)-该帖子中的两个答案都会非常有帮助。祝好运。 - EdSF
谢谢@EdSF,但我仍然有一个未解决的问题,即组织应用程序的最佳方式是使用字符串GUID还是GUID(唯一标识符)作为ID? - Ostap
1
这取决于_您的_要求。请参考Rick Anderson (MSFT)的答案以获得指导。 - EdSF
2个回答

14

使用ASP.NET Core,您可以非常简单地指定Identity模型所需的数据类型。

第一步,将Identity类从< string>覆盖为< 您想要的数据类型>

public class ApplicationUser : IdentityUser<Guid>
{
}

public class ApplicationRole : IdentityRole<Guid>
{
}

声明您的数据库上下文,使用您的类和所需的数据类型:

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);
        }
    }

在你的启动类中,使用你的模型声明身份服务,并声明你想要用于主键的数据类型:

services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext, Guid>()
            .AddDefaultTokenProviders();

3
有关此信息,现在官方文档中有相关主题:https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-primary-key-configuration。 - AdrienTorris

3
根据您所使用的ASP.Net身份验证版本,ASP.NET Identity v2应将其存储为唯一标识符(Guid)存储在AspNetUsers表中。在更早的版本中,它将用户ID存储为webpages_Membership表中的int类型。我认为它将其呈现为字符串,因此在幕后可以是任何数据类型,并且可以根据需要在代码中进行转换。

嗨,Tim,我正在使用ASP.NET的最新版本会员系统 - ASP.NET Identity。我仍然不确定,在我的数据库中使用字符串作为所有表的最佳实践,还是将所有内容转换为GUID? - Ostap
@user3460585 int和Guid是一个古老的争论话题。请参考以下答案:http://dba.stackexchange.com/a/266/6868 http://blog.codinghorror.com/primary-keys-ids-versus-guids/ http://programmers.stackexchange.com/a/189031/86760 - trailmax
1
抱歉,我没有意识到您在询问数据库。通常我们会将用户名存储在数据库中的用户记录中,然后可以引用ASP.Net记录,这也使您与底层成员资格层分离。 - Tim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接