2015-12-29 13 views
16

Standardmäßig verwendet ASP.NET Identity in VS 2015 eine Zeichenfolge als Primärschlüssel für AspNet *** -Tabellen. Ich wollte stattdessen int-typisierte IDs verwenden. Nach einiger Recherche stellte sich heraus, dass verschiedene typisierte IDs vom Framework aus der Box unterstützt werden. In der folgenden Antwort werde ich zeigen, welche Änderungen vorgenommen werden müssen, um dies zu erreichen.Ändern des Benutzerid-Typs in int in ASP.NET Identity in VS2015

UPDATE: Nach meiner Antwort Zugabe fand ich diese Blog-Post auf asp.net Website, die die gleiche, aber umfassender beschrieben: http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity

Antwort

28
  1. IdentityModels.cs Änderung dieses:

    // 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, ändern Sie die folgenden Klassen:

    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 ändern OnValidateIdentity Eigenschaft auf diese:

    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
        validateInterval: TimeSpan.FromMinutes(30), 
        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager), 
        getUserIdCallback: id => id.GetUserId<int>()) 
    
  4. ändern ManageController mit dem neuen Stück Art zu arbeiten:

Ersetzen Sie alle Einträge von User.Identity.GetUserId()-User.Identity.GetUserId<int>()

Es könnte sein, Paar von String id Argumente, die geändert werden müssen, um int, aber das ist es.

+0

Wenn Sie genau markieren könnten, was in Ihrem Code die Int-ID erstellt, wäre das großartig thx. – niico

+0

Sollten wir die automatische Erhöhung der Id der Benutzer-Tabelle aktivieren? – Reza

+0

@niico - soweit ich mich erinnere, die ID-Felder in der Auth db wurden auf Auto-Inkrement gesetzt – Andrey

6

Per this blog post, mit ASP.NET Core-Identität, die folgenden Änderungen:

Zuerst gehen Sie auf die Data\Migrations Ordner und löschen Sie alles drin.

In Startup.cs im ConfigureServices Methode ändern services.AddIdentity zu

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

In ApplicationDbContext.cs Änderung der Basisklasse von IdentityDbContext<ApplicationUser> zu

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

schließlich die Basisklasse ändern in ApplicationUser.cs von IdentityUser zu

public class ApplicationUser : IdentityUser<int> 

Dann führen Sie add-migration -o Data\Migrations und update-database. Wenn die Migrationen Probleme verursachen, verwenden Sie Sql Server Management Studio oder SqlServerObjectExplorer in VS, um die Datenbank zu löschen (nicht Verwenden Sie einfach das Dateisystem), löschen Sie Ihre Migrationen erneut und versuchen Sie es erneut.

Verwandte Themen