当前位置:  开发笔记 > 编程语言 > 正文

在VS2015中的ASP.NET标识中将用户标识类型更改为int

如何解决《在VS2015中的ASP.NET标识中将用户标识类型更改为int》经验,为你挑选了2个好方法。

默认情况下,VS 2015中的ASP.NET身份使用字符串作为AspNet***表的主键.我想改用int-typed id.经过一些研究后发现,开箱即用的框架支持不同类型的id.在下面的答案中,我将展示为实现这一目标所做的更改.

更新:在添加我的答案后,我在asp.net网站上发现了这篇博文,描述了相同但更全面的内容:http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-在-ASPNET身份



1> Andrey..:

    IdentityModels.cs 改为:

    // New derived classes
    public class UserRole : IdentityUserRole
    {
    }
    
    public class UserClaim : IdentityUserClaim
    {
    }
    
    public class UserLogin : IdentityUserLogin
    {
    }
    
    public class Role : IdentityRole
    {
        public Role() { }
        public Role(string name) { Name = name; }
    }
    
    public class UserStore : UserStore
    {
        public UserStore(ApplicationDbContext context): base(context)
        {
        }
    }
    
    public class RoleStore : RoleStore
    {
        public RoleStore(ApplicationDbContext context): base(context)
        {
        }
    }
    
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
        public DateTime? ActiveUntil;
    
        public async Task GenerateUserIdentityAsync(ApplicationUserManager manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }
    
    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    
        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
    

    在`App_Start\IdentityConfig.cs中,更改以下类:

    public class ApplicationUserManager : UserManager
    {
        public ApplicationUserManager(IUserStore store)
            : base(store)
        {
        }
    
        public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context) 
        {
            var manager = new ApplicationUserManager(new UserStore(context.Get()));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };
    
            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 8,
                // RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };
    
            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;
    
            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = 
                    new DataProtectorTokenProvider(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }
    }
    
    // Configure the application sign-in manager which is used in this application.
    public class ApplicationSignInManager : SignInManager
    {
        public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
            : base(userManager, authenticationManager)
        {
        }
    
        public override Task CreateUserIdentityAsync(ApplicationUser user)
        {
            return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
        }
    
        public static ApplicationSignInManager Create(IdentityFactoryOptions options, IOwinContext context)
        {
            return new ApplicationSignInManager(context.GetUserManager(), context.Authentication);
        }
    }
    

    App_Start\Startup.Auth.cs更改OnValidateIdentity属性中:

    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity(
        validateInterval: TimeSpan.FromMinutes(30),
        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
        getUserIdCallback: id => id.GetUserId())
    

    更改ManageController以使用新的pk类型:

替换的所有条目User.Identity.GetUserId()User.Identity.GetUserId()

可能有一些id需要更改的字符串参数int,但这就是它.


如果您可以准确地突出显示代码中创建int id的内容,那将是非常好的。

2> Michael Tran..:

根据此博客文章,使用ASP.NET Core Identity,进行以下更改:

首先,转到该Data\Migrations文件夹并删除其中的所有内容.

Startup.cs,ConfigureServices方法中,services.AddIdentity改为

services.AddIdentity>()
   .AddEntityFrameworkStores()
   .AddDefaultTokenProviders();

ApplicationDbContext.cs改变从基类IdentityDbContext

public class ApplicationDbContext
  : IdentityDbContext, int>

最后,在更改基类ApplicationUser.csIdentityUser

public class ApplicationUser : IdentityUser

然后运行add-migration -o Data\Migrationsupdate-database.如果迁移导致任何问题,请使用VS中的Sql Server Management Studio或SqlServerObjectExplorer删除数据库(不要只使用文件系统),重新删除迁移,然后重试.


对于.NET Core 2. *及更高版本,将`.AddEntityFrameworkstores <ApplicationDbContext,int>()`更改为`.AddEntityFrameworkStores <ApplicationDbContext>()`即可。
推荐阅读
雯颜哥_135
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有