问题描述
在默认情况下ASP.NET的身份在2015年VS使用一个字符串作为主键ASPNET ***表。我想用INT类型的的ID来代替。经过一番研究,事实证明,不同的类型化ID是由框架开箱即用的支持。在回答以下我将展示什么样的变化,使以实现这一目标。
更新:加入我的回答后,我发现在asp.net网站这个博客帖子描述相同,但多个COM prehensive:http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity
-
IdentityModels.cs
改成这样://新的派生类
公共类的UserRole:IdentityUserRole< INT>
{
}公共类UserClaim:IdentityUserClaim<&诠释GT;
{
}公共类用户登陆:IdentityUserLogin<&诠释GT;
{
}公共类角色:IdentityRole< INT,UserRole的>
{
公共角色(){}
公共角色(字符串名称){名称=名称; }
}公共类UserStore:UserStore< ApplicationUser,角色,INT,
用户登陆,UserRole的,UserClaim>
{
公共UserStore(ApplicationDbContext上下文):基地(上下文)
{
}
}公共类Rolestore的:Rolestore的<作用,INT的UserRole>
{
公共Rolestore的(ApplicationDbContext上下文):基地(上下文)
{
}
}//你可以通过添加更多的属性你ApplicationUser类用户添加配置文件数据,请访问http://go.microsoft.com/fwlink/?LinkID=317594,以了解更多信息。
公共类ApplicationUser:IdentityUser< INT,用户登陆,UserRole的,UserClaim>
{
公众的DateTime? ActiveUntil; 公共异步任务< ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager经理)
{
//注意authenticationType必须CookieAuthenticationOptions.AuthenticationType定义的匹配
VAR的UserIdentity =等待manager.CreateIdentityAsync(这一点,DefaultAuthenticationTypes.ApplicationCookie);
//添加自定义的用户在这里声明
返回的UserIdentity;
}
}公共类ApplicationDbContext:IdentityDbContext< ApplicationUser,角色,INT,
用户登陆,UserRole的,UserClaim>
{
公共ApplicationDbContext()
:基地(DefaultConnection)
{
} 公共静态ApplicationDbContext的Create()
{
返回新ApplicationDbContext();
}
} -
在`App_Start \\ IdentityConfig.cs,更改以下类:
公共类ApplicationUserManager:&的UserManager LT; ApplicationUser,INT>
{
公共ApplicationUserManager(IUserStore< ApplicationUser,INT>存储)
:基地(存储)
{
} 公共静态ApplicationUserManager创建(IdentityFactoryOptions< ApplicationUserManager>选项,IOwinContext上下文)
{
VAR经理=新ApplicationUserManager(新UserStore(context.Get< ApplicationDbContext>()));
//配置用户名验证逻辑
manager.UserValidator =新UserValidator< ApplicationUser,INT>(经理)
{
AllowOnlyAlphanumericUserNames =假,
RequireUniqueEmail =真
}; //配置密码验证逻辑
manager.PasswordValidator =新PasswordValidator
{
RequiredLength = 8,
// RequireNonLetterOrDigit = TRUE,
RequireDigit = TRUE,
RequireLowercase = TRUE,
RequireUppercase = TRUE,
}; //配置用户锁定默认
manager.UserLockoutEnabledByDefault = TRUE;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5; //注册双因素身份验证提供者。此应用程序使用手机和电子邮件作为接收code用于验证用户的步骤
//你可以写自己的供应商,并在这里插入。
manager.RegisterTwoFactorProvider(手机code,新PhoneNumberTokenProvider< ApplicationUser,INT>
{
MessageFormat =您的安全code是{0}
});
manager.RegisterTwoFactorProvider(电子邮件code,新EmailTokenProvider< ApplicationUser,INT>
{
主题=安全code,
BodyFormat =您的安全code是{0}
});
manager.EmailService =新EmailService();
manager.SmsService =新SmsService();
VAR dataProtectionProvider = options.DataProtectionProvider;
如果(dataProtectionProvider!= NULL)
{
manager.UserTokenProvider =
新DataProtectorTokenProvider< ApplicationUser,INT>(dataProtectionProvider.Create(ASP.NET身份));
}
返回经理;
}
}//配置应用程序登录管理器,它是本应用中使用。
公共类ApplicationSignInManager:SignInManager< ApplicationUser,INT>
{
公共ApplicationSignInManager(ApplicationUserManager的UserManager,IAuthenticationManager AuthenticationManager会)
:基地(的UserManager,AuthenticationManager会)
{
} 公共覆盖任务< ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser用户)
{
返回user.GenerateUserIdentityAsync((ApplicationUserManager)的UserManager);
} 公共静态ApplicationSignInManager创建(IdentityFactoryOptions< ApplicationSignInManager>选项,IOwinContext上下文)
{
返回新ApplicationSignInManager(context.GetUserManager< ApplicationUserManager>(),context.Authentication);
}
} -
在
App_Start \\ Startup.Auth.cs
变更OnValidateIdentity
属性如下:OnValidateIdentity = SecurityStampValidator.OnValidateIdentity< ApplicationUserManager,ApplicationUser,INT>(
validateInterval:TimeSpan.FromMinutes(30),
regenerateIdentityCallback:(经理,用户)=> user.GenerateUserIdentityAsync(经理)
getUserIdCallback:ID => id.GetUserId< INT>()) -
更改ManageController与新的PK类型的工作:
替换 User.Identity.GetUserId的所有条目()
到 User.Identity.GetUserId< INT>()
有可能是一对夫妇的字符串需要更改为
参数,但仅此而已 INT
ID
By default ASP.NET Identity in VS 2015 uses a string as a primary key for AspNet*** tables. I wanted to to use int-typed id's instead. After some research it turned out that different typed id's are supported by the framework out of the box. In the answer below I will show what changes to make to achieve that.
UPDATE: After adding my answer I found this blog post on asp.net site that describes the same but more comprehensive: http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity
IdentityModels.cs
change to this:// 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(); } }
In `App_Start\IdentityConfig.cs, change the following classes:
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); } }
In
App_Start\Startup.Auth.cs
changeOnValidateIdentity
property to this:OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager), getUserIdCallback: id => id.GetUserId<int>())
Change ManageController to work with the new pk type:
Replace all entries of User.Identity.GetUserId()
to User.Identity.GetUserId<int>()
There might be a couple of string id
arguments that need to be changed to int
, but that's about it.
这篇关于更改用户ID类型在ASP.NET中的身份为int在VS2015的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!