2015-12-29 5 views
16

Domyślnie tożsamość ASP.NET w usłudze VS 2015 używa ciągu znaków jako klucza podstawowego w tabelach AspNet ***. Zamiast tego chciałem użyć identyfikatora typu int. Po pewnych badaniach okazało się, że różne typowe identyfikatory są obsługiwane przez framework po wyjęciu z pudełka. W poniższej odpowiedzi pokażę, jakie zmiany należy wprowadzić, aby to osiągnąć.Zmiana typu identyfikatora użytkownika na int w tożsamości ASP.NET w VS2015

UPDATE: Po dodaniu moją odpowiedź znalazłem ten wpis na blogu na stronie asp.net, który opisuje to samo, ale bardziej wszechstronny: http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity

Odpowiedz

28
  1. IdentityModels.cs zmiany to:

    // 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. W `App_Start \ IdentityConfig.cs, zmień następujące klasy:

    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. W App_Start\Startup.Auth.cs zmiany OnValidateIdentity własności do tego:

    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
        validateInterval: TimeSpan.FromMinutes(30), 
        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager), 
        getUserIdCallback: id => id.GetUserId<int>()) 
    
  4. Zmień ManageController do pracy z nowym typem pk:

zastąpić wszystkie wpisy User.Identity.GetUserId() do User.Identity.GetUserId<int>()

Może być kilka argumentów, które należy zmienić na int, ale to już wszystko.

+0

Jeśli mógłbyś podświetlić dokładnie to, co w kodzie tworzyło int id, który byłby świetny thx. – niico

+0

Czy powinniśmy włączyć automatyczną inkrementację w tabeli Identyfikatory użytkowników? – Reza

+0

@niico - o ile pamiętam, pola id w auth db były ustawione na auto increment – Andrey

6

Per this blog post, z ASP.NET podstawowa tożsamość, wprowadzić następujące zmiany:

pierwsze, przejdź do folderu Data\Migrations i usunąć wszystko tam.

W Startup.cs w sposobie ConfigureServices zmienić services.AddIdentity do

services.AddIdentity<ApplicationUser, IdentityRole<int>>() 
    .AddEntityFrameworkStores<ApplicationDbContext, int>() 
    .AddDefaultTokenProviders(); 

W ApplicationDbContext.cs zmianę klasy bazowej z IdentityDbContext<ApplicationUser> do

public class ApplicationDbContext 
    : IdentityDbContext<ApplicationUser, IdentityRole<int>, int> 

Wreszcie zmianę klasy bazowej w ApplicationUser.cs z IdentityUser do

public class ApplicationUser : IdentityUser<int> 

Następnie uruchom add-migration -o Data\Migrations i update-database. Jeśli migracje powodują jakiekolwiek problemy, użyj Sql Server Management Studio lub SqlServerObjectExplorer w VS, aby usunąć bazę danych (nie używaj po prostu użyj systemu plików), ponownie usuń swoje migracje i spróbuj ponownie.

Powiązane problemy