ASP.NET Identity 2.0 Change Primary Key from String to Integer
来源:互联网 发布:小学生拼音软件下载 编辑:程序博客网 时间:2024/06/14 18:00
Introduction
User’s entry tracking is essential for some project. A common example is accounting software. Asp.net identity framework 1.0 use string (128 char) as userId. If an application work with huge amount of data then retrieve information with user’s info may slow because of string matching. In that case Integer is the best solution.
Latest Identity framework 2.0 comes with some new features. One of them is generic primary key. So now, we can make primary key integer or whatever we like. Identity 2.0 included in Visual Studio 2013 update 2 (released May 12, 2014).
Using the code
In this article we are going to change primary key data type from string to int with bellow steps
- Create a MVC project using Visual Studio 2013 update 2
- Create & change Identity classes
- Change account controller to work with new primary key
Create a MVC project using Visual Studio 2013 update 2
Lets create a new ASP.Net web application named Identity2IntPK using Visual Studio 2013. Next select MVCwith Individual User Account.
Visual Studio 2013 MVC template will create a structure like this image.
IdentityConfig file contain a class ApplicationUserManager where we can set password strength.
Startup.Auth contain a partial class Startup. Here we can set 3rd party login provider like facebook, google etc.
IdentityModels contain ApplicationUser & ApplicationDbContext. Basically we are going to change this file.
AccountViewModels contain some classes uses for data transfer & validation.
AccountController has only AccountController class which responsible for login, registration, password reset & others.
Account this folder contain some view files such as Login.cshtml, Register.cshtml, ResetPassword.cshtml.
Create & change Identity classes
We have to change bellow files to finish this task.
- IdentityModels.cs
- IdentityConfig.cs
- Startup.Auth.cs
1. IdentityModels.cs : Open file form Modules folder & add UserRoleIntPk, UserClaimIntPk, UserLoginIntPk, RoleIntPk, UserStoreIntPk, RoleStoreIntPk classes.
//New drived classes public class UserRoleIntPk : IdentityUserRole<int> { } public class UserClaimIntPk : IdentityUserClaim<int> { } public class UserLoginIntPk : IdentityUserLogin<int> { } public class RoleIntPk : IdentityRole<int, UserRoleIntPk> { public RoleIntPk() { } public RoleIntPk(string name) { Name = name; } } public class UserStoreIntPk : UserStore<ApplicationUser, RoleIntPk, int, UserLoginIntPk, UserRoleIntPk, UserClaimIntPk> { public UserStoreIntPk(ApplicationDbContext context) : base(context) { } } public class RoleStoreIntPk : RoleStore<RoleIntPk, int, UserRoleIntPk> { public RoleStoreIntPk(ApplicationDbContext context) : base(context) { } }
Also change ApplicationUser & ApplicationDbContext in same file.
//change bellow classes public class ApplicationUser : IdentityUser<int, UserLoginIntPk, UserRoleIntPk, UserClaimIntPk> { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager) { var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser, RoleIntPk, int, UserLoginIntPk, UserRoleIntPk, UserClaimIntPk> { public ApplicationDbContext() : base("DefaultConnection") { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } }
2. IdentityConfig.cs: Open this file from App_Start folder & change ApplicationUserManagerclass. After change ApplicationUserManager will looks like:
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 UserStoreIntPk(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 = 6, //RequireNonLetterOrDigit = true, //RequireDigit = true, //RequireLowercase = true, //RequireUppercase = true, }; manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<ApplicationUser, int> { MessageFormat = "Your security code is: {0}" }); manager.RegisterTwoFactorProvider("EmailCode", 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; } }
Here we replace <ApplicationUser> with <ApplicationUser, int>
3. Startup.Auth.cs: Open this file from App_Start folder & change old code with new code.
//old code OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
//New code OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int> ( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager), getUserIdCallback: (id) => (Int32.Parse(id.GetUserId())) )
Change account controller to work with new primary key
Our work is almost done. If you compile your code you get almost 16 errors & all are in AccountController.csfile. So we have to change this file to work with new system.
Open AccountController.cs & change all userId type from string to int. Then replace allUser.Identity.GetUserId() with int.Parse(User.Identity.GetUserId()) except LinkLogin function.
Also LinkLoginCallback change to
//// GET: /Account/LinkLoginCallbackpublic async Task<ActionResult> LinkLoginCallback(){ var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId()); if (loginInfo == null) { return RedirectToAction("Manage", new { Message = ManageMessageId.Error }); } IdentityResult result = await UserManager.AddLoginAsync(int.Parse(User.Identity.GetUserId()), loginInfo.Login); if (result.Succeeded) { return RedirectToAction("Manage"); } return RedirectToAction("Manage", new { Message = ManageMessageId.Error });}
Running the Application
Now compile your project & if everything is fine then run it. Click register from navigation menu & add an user.
Entity framework will create a database for you with AspNet authorization tables. If you like to check what happened in database then open DefaultConnection from server explorer. right click on AspNetUsers table & select open table definition, you will see id is now int instead of string.
Points of Interest
Identity 2 is great because it comes with a lot of useful things. But default identity system may not all time compatible with all application. That is why this article may helpful for those who want more extensibility.
http://www.codeproject.com/Articles/777733/ASP-NET-Identity-Change-Primary-Key
- ASP.NET Identity 2.0 Change Primary Key from String to Integer
- INTEGER PRIMARY KEY简介
- INTEGER PRIMARY KEY简介
- Converting string to/from integer
- [ASP.NET Identity 2.0]
- How to delete duplicate records from tables without Primary key
- INTEGER PRIMARY KEY AUTOINCREMENT 和 INTEGER PRIMARY KEY 区别
- Upgrading from ASP.NET 1.1 to 2.0
- Sqlite中INTEGER PRIMARY KEY的修正
- 简述PRIMARY KEY与identity(1,1)的含义
- PRIMARY KEY主键和IDENTITY属性函数的区别
- PRIMARY KEY与identity(1,1)的比较
- 简述PRIMARY KEY与identity(1,1)的含义
- asp.net identity
- ASP.NET Identity
- ASP.NET Identity Authentication
- ASP.NET Identity简介
- ASP.NET Identity
- XHR XMLHttpRequest
- 2014总结,一起说……
- jsp page指令详解
- OSChina 技术周刊第二十一期——下一代 ECharts
- 面试算法001-- 把二元查找树转变成排序的双向链表
- ASP.NET Identity 2.0 Change Primary Key from String to Integer
- 全关联优化
- JSP内置对象(一)——request对象
- Eclipse执行java代码,获取系统时间少了8个小时,解决办法
- 基本数据类型包装类的简单介绍及进制转换
- Android API之android.provider.ContactsContract.RawContacts
- Mysql 报错:master and slave have equal MySQL server UUIDs
- POJ-1251 Jungle Roads(最小生成树)
- 开门大吉