2015-12-29 22 views
16

Theo mặc định ASP.NET Identity trong VS 2015 sử dụng chuỗi làm khóa chính cho bảng AspNet ***. Thay vào đó, tôi muốn sử dụng id được nhập int. Sau khi một số nghiên cứu nó bật ra rằng id đánh máy khác nhau được hỗ trợ bởi khuôn khổ ra khỏi hộp. Trong câu trả lời dưới đây tôi sẽ cho thấy những thay đổi cần thực hiện để đạt được điều đó.Thay đổi loại Id người dùng thành int trong ASP.NET Identity trong VS2015

UPDATE: Sau khi thêm câu trả lời của tôi, tôi tìm thấy bài viết trên blog này trên trang web asp.net mô tả giống nhau nhưng toàn diện hơn: http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity

Trả lời

28
  1. IdentityModels.cs thay đổi này:

    // 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. Trong `App_Start \ IdentityConfig.cs, thay đổi các lớp sau:

    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. Trong App_Start\Startup.Auth.cs thay đổi OnValidateIdentity tài sản như sau:

    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
        validateInterval: TimeSpan.FromMinutes(30), 
        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager), 
        getUserIdCallback: id => id.GetUserId<int>()) 
    
  4. Thay đổi ManageController để làm việc với các loại pk mới:

Thay thế tất cả các mục của User.Identity.GetUserId()-User.Identity.GetUserId<int>()

Có thể có một một vài chuỗi id đối số cần phải được thay đổi thành int, nhưng đó là về nó.

+0

Nếu bạn có thể làm nổi bật chính xác những gì trong mã của bạn đang tạo id int sẽ là tuyệt vời thx. – niico

+0

Chúng tôi có nên bật tăng tự động trên Id được lưu của bảng Người dùng không? – Reza

+0

@niico - theo như tôi nhớ các trường id trong db xác thực được đặt thành tăng tự động – Andrey

6

mỗi this blog post, với ASP.NET Lõi Identity, làm cho những thay đổi sau:

Trước tiên, hãy vào thư mục Data\Migrations và xóa tất cả mọi thứ trong đó.

Trong Startup.cs, trong phương pháp ConfigureServices, thay đổi services.AddIdentity để

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

Trong ApplicationDbContext.cs thay đổi các lớp cơ sở từ IdentityDbContext<ApplicationUser> để

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

Cuối cùng, thay đổi lớp cơ sở trong ApplicationUser.cs từ IdentityUser để

public class ApplicationUser : IdentityUser<int> 

Sau đó, chạy add-migration -o Data\Migrationsupdate-database. Nếu việc di chuyển gây ra bất kỳ vấn đề nào, hãy sử dụng Sql Server Management Studio hoặc SqlServerObjectExplorer trong VS để xóa cơ sở dữ liệu (không chỉ sử dụng hệ thống tệp), xóa lại di chuyển của bạn và thử lại.

Các vấn đề liên quan