2015-12-29 16 views
16

Per impostazione predefinita, l'identità di ASP.NET in VS 2015 utilizza una stringa come chiave primaria per le tabelle di AspNet ***. Volevo usare invece gli ID int-typed. Dopo alcune ricerche è emerso che diversi ID tipizzati sono supportati dal framework fuori dalla scatola. Nella risposta qui sotto mostrerò quali modifiche apportare per ottenere ciò.Cambia il tipo di ID utente in int nell'identità ASP.NET in VS2015

UPDATE: Dopo aver aggiunto la mia risposta ho trovato questo post del blog sul sito asp.net che descrive lo stesso, ma più completo: http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity

risposta

28
  1. IdentityModels.cs modifica a questo:

    // 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. In `App_Start \ IdentityConfig.cs, modificare le seguenti classi:

    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. In App_Start\Startup.Auth.cs cambiamento OnValidateIdentity immobili a questo:

    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
        validateInterval: TimeSpan.FromMinutes(30), 
        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager), 
        getUserIdCallback: id => id.GetUserId<int>()) 
    
  4. Change ManageController di lavorare con il nuovo tipo di pk:

sostituire tutte le voci di User.Identity.GetUserId()-User.Identity.GetUserId<int>()

Ci potrebbe essere un un paio di argomenti stringa id che devono essere modificati in int, ma questo è tutto.

+0

Se potessi evidenziare esattamente ciò che nel tuo codice stava creando l'int id che sarebbe ottimo thx. – niico

+0

Dovremmo abilitare l'incremento automatico sulla tabella ID depositata degli utenti ?? – Reza

+0

@niico: per quanto mi ricordo, i campi ID in auth db erano impostati su incremento automatico – Andrey

6

Per this blog post, con ASP.NET Nucleo Identità, apportare le seguenti modifiche:

In primo luogo, andare alla cartella Data\Migrations e cancellare tutto lì dentro.

In Startup.cs, nel metodo ConfigureServices, cambiare services.AddIdentity a

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

In ApplicationDbContext.cs modifica la classe di base da IdentityDbContext<ApplicationUser> a

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

Infine modificare la classe base in ApplicationUser.cs da IdentityUser a

public class ApplicationUser : IdentityUser<int> 

Quindi eseguire add-migration -o Data\Migrations e update-database. Se le migrazioni causano problemi, utilizzare Sql Server Management Studio o SqlServerObjectExplorer in VS per eliminare il database (non utilizzare solo per utilizzare il file system), eliminare di nuovo le migrazioni e riprovare.