gpt4 book ai didi

asp.net - 将 VS2015 中的 ASP.NET Identity 中的 User Id 类型更改为 int

转载 作者:行者123 更新时间:2023-12-02 07:22:31 25 4
gpt4 key购买 nike

默认情况下,VS 2015 中的 ASP.NET Identity 使用字符串作为 AspNet*** 表的主键。我想使用 int 类型的 id 来代替。经过一些研究后发现,框架开箱即用地支持不同类型的 ID。在下面的答案中,我将展示要实现这一目标需要进行哪些更改。

更新:添加我的答案后,我在 ASP.NET 网站上发现了这篇博客文章,它描述了相同但更全面:http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity

最佳答案

  1. IdentityModels.cs更改为:

    // New derived classes
    public class UserRole : IdentityUserRole<int>
    {
    }

    public class UserClaim : IdentityUserClaim<int>
    {
    }

    public class UserLogin : IdentityUserLogin<int>
    {
    }

    public class Role : IdentityRole<int, UserRole>
    {
    public Role() { }
    public Role(string name) { Name = name; }
    }

    public class UserStore : UserStore<ApplicationUser, Role, int,
    UserLogin, UserRole, UserClaim>
    {
    public UserStore(ApplicationDbContext context): base(context)
    {
    }
    }

    public class RoleStore : RoleStore<Role, int, UserRole>
    {
    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<int, UserLogin, UserRole, UserClaim>
    {
    public DateTime? ActiveUntil;

    public async Task<ClaimsIdentity> 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<ApplicationUser, Role, int,
    UserLogin, UserRole, UserClaim>
    {
    public ApplicationDbContext()
    : base("DefaultConnection")
    {
    }

    public static ApplicationDbContext Create()
    {
    return new ApplicationDbContext();
    }
    }
  2. 在 `App_Start\IdentityConfig.cs 中,更改以下类:

    public class ApplicationUserManager : UserManager<ApplicationUser, int>
    {
    public ApplicationUserManager(IUserStore<ApplicationUser, int> store)
    : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
    var manager = new ApplicationUserManager(new UserStore(context.Get<ApplicationDbContext>()));
    // Configure validation logic for usernames
    manager.UserValidator = new UserValidator<ApplicationUser, int>(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<ApplicationUser, int>
    {
    MessageFormat = "Your security code is {0}"
    });
    manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser, int>
    {
    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<ApplicationUser, int>(dataProtectionProvider.Create("ASP.NET Identity"));
    }
    return manager;
    }
    }

    // Configure the application sign-in manager which is used in this application.
    public class ApplicationSignInManager : SignInManager<ApplicationUser, int>
    {
    public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
    : base(userManager, authenticationManager)
    {
    }

    public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
    {
    return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
    }

    public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
    {
    return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
    }
    }
  3. App_Start\Startup.Auth.cs更改OnValidateIdentity属性为:

    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
    validateInterval: TimeSpan.FromMinutes(30),
    regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
    getUserIdCallback: id => id.GetUserId<int>())
  4. 更改 ManageController 以使用新的 pk 类型:

替换 User.Identity.GetUserId() 的所有条目至User.Identity.GetUserId<int>()

可能有几个字符串 id需要更改为 int 的参数,但仅此而已。

关于asp.net - 将 VS2015 中的 ASP.NET Identity 中的 User Id 类型更改为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34505904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com