Why asp.net Identity user id is string?

假装没事ソ 提交于 2020-04-29 06:51:46

问题


I want to use System.Guid type as an id for all of my tables in asp.net web api application. But I also use Asp.net Identity, which using a string-type id (to store guids as well). So I wonder why is it using string id instead of System.Guid by default? And what is better choice to use through all the application - Guid id or string-guid id? In case of using string - what is the most proper and reliable way to generate new id - in code or in database?


回答1:


With ASP.NET Core, you have a very simple way to specify the data type you want for Identity's models.

First step, override identity classes from < string> to < data type you want> :

public class ApplicationUser : IdentityUser<Guid>
{
}

public class ApplicationRole : IdentityRole<Guid>
{
}

Declare your database context, using your classes and the data type you want :

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

And in your startup class, declare the identity service using your models and declare the data type you want for the primary keys :

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



回答2:


Depending on which version of ASP.Net authentication you're using, on the database ASP.NET Identity v2 should be storing it as a uniqueidentifier (Guid) in the AspNetUsers table. In more preceding versions it will store the user id as an int in the webpages_Membership table.

I believe it surfaces it as a string so it can be any data type you like under the hood and this can then be cast within your code as required.



来源:https://stackoverflow.com/questions/30029182/why-asp-net-identity-user-id-is-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!