扩展ASP.NET Identity使用Int做主键
当我们默认新建一个ASP.NET MVC项目的时候,使用的身份认证系统是ASP.NET Identity.
但是这里的Identity使用的主键为String类型的GUID.当然这是大多数系统首先类型.
但是因为历史原因,而我们公司所有项目主键都是用的Int类型(这里不讨论int和GUID的优劣)
所以默认的String类型GUID就不能满足我们的需求,所以进行一些扩展,让其支持Int类型。
下图为默认使用String做主键的ASP.NET MVC
ApplicationUser继承自IdentityUser,而IdentityUser继承/实现
IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser, IUser<string>
这样就使得主键为string类型了,其中IentityUser,IdentityUserLogin,IdentityUserRole,IdentityUserClaim都是<string>
所以生成默认的数据库里的表结构成了下图这样,主键都为nvarchar

接下来,扩展为Int主键首先增加如下几个类
public class ApplicationUserLogin : IdentityUserLogin<int> { }
public class ApplicationUserCliam : IdentityUserClaim<int> { }
public class ApplicationUserRole : IdentityUserRole<int> { }
public class ApplicationRole : IdentityRole<int, ApplicationUserRole>, IRole<int> {
public string Description { get; set; }
public ApplicationRole() { }
public ApplicationRole(string name)
: this()
{
this.Name = name;
}
public ApplicationRole(string name, string description)
: this(name)
{
this.Description = description;
}
}
ApplicationUserLogin 继承自IdentityUserLogin<int>
ApplicationUserCliam 继承自IdentityUserClaim<int>
ApplicationUserRole 继承自IdentityUserRole<int>
ApplicationRole 继承自IdentityRole<int, ApplicationUserRole>, IRole<int>
在Role里还增加了一个属性Deacription(默认实体里只有Id,Name)
做了这步后。其实在Code first中,我们就已经把实体的结构主键修改为int型了,
只要用这个对应实体Update到数据库中的话。主键会修改成int
然后我们还要对应ASP.NET MVC的一些改造才可以适应现有的模板
然后我们将ApplicationUser修改
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// 请注意,authenticationType 必须与 CookieAuthenticationOptions.AuthenticationType 中定义的相应项匹配
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// 在此处添加自定义用户声明
return userIdentity;
}
}
修改为:
public class ApplicationUser
: IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserCliam>, IUser<int>
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
// 请注意,authenticationType 必须与 CookieAuthenticationOptions.AuthenticationType 中定义的相应项匹配
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// 在此处添加自定义用户声明
return userIdentity;
}
}
接下来我们要修改数据库上下文ApplicationDbContext
修改为
public class ApplicationDbContext
: IdentityDbContext<ApplicationUser, ApplicationUserRole, int,
ApplicationUserLogin, ApplicationUserRole, ApplicationUserCliam>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
然后在增加如下两个类
public class ApplicationUserStore
: UserStore<ApplicationUser, ApplicationRole, int,
ApplicationUserLogin, ApplicationUserRole, ApplicationUserCliam>,
IUserStore<ApplicationUser, int>,
IDisposable
{
public ApplicationUserStore(DbContext context)
: base(context)
{ }
public ApplicationUserStore()
: this(new IdentityDbContext())
{
base.DisposeContext = true;
}
}
public class ApplicationRoleStore
: RoleStore<ApplicationRole, int, ApplicationUserRole>,
IQueryableRoleStore<ApplicationRole, int>,
IRoleStore<ApplicationRole>,
IDisposable
{
public ApplicationRoleStore()
: base(new IdentityDbContext())
{
base.DisposeContext = true;
}</span><span style="color: #0000ff">public</span><span style="color: #000000"> ApplicationRoleStore(DbContext context)
: </span><span style="color: #0000ff">base</span><span style="color: #000000">(context)
{
}
}</span></pre></div>
上面的几处代码全修改在IdentityModels.cs文件中
然后修改App_Start\IdentityConfig.cs
在类ApplicationUserManager和ApplicationSignInManager中
把里面所有继承自<ApplicationRole>泛型的地址全部都修改为<ApplicationRole,int>
public class ApplicationUserManager : UserManager<ApplicationUser,int>
public ApplicationUserManager(IUserStore<ApplicationUser, int> store)
manager.UserValidator = new UserValidator<ApplicationUser, int>(manager)
manager.RegisterTwoFactorProvider("电话代码", new PhoneNumberTokenProvider<ApplicationUser,int>
manager.RegisterTwoFactorProvider("电子邮件代码", new EmailTokenProvider<ApplicationUser,int>
public class ApplicationSignInManager : SignInManager<ApplicationUser, int>在App_Start\Startup.Auth.cs
把配置登陆Cookie的代码修改为app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// 当用户登录时使应用程序可以验证安全戳。
// 这是一项安全功能,当你更改密码或者向帐户添加外部登录名时,将使用此功能。
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
getUserIdCallback: (claim) => int.Parse(claim.GetUserId()))
//regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});到此,所有的扩展都已经修改完成,接下来就只要修改相关的View和Controller
在AccountController和ManageController中,
主要是把用到User.Identity.GetUserId()的地方修改为User.Identity.GetUserId<int>();
这样使得拿到的主键由string变成了int接下来运行程序包管理控制台,生成数据库脚本并执行到数据库
PM> Enable-Migrations
正在检查上下文的目标是否为现有数据库...
已为项目 IntegerDemo 启用 Code First 迁移。
PM> Add-Migration FirstInit
正在为迁移“FirstInit”搭建基架。
此迁移文件的设计器代码包含当前 Code First 模型的快照。在下一次搭建迁移基架时,将使用此快照计算对模型的更改。如果对要包含在此迁移中的模型进行其他更改,则您可通过再次运行“Add-Migration FirstInit”重新搭建基架。
PM> Update-Database
指定“-Verbose”标志以查看应用于目标数据库的 SQL 语句。
正在应用显式迁移: [201506240620390_FirstInit]。
正在应用显式迁移: 201506240620390_FirstInit。
正在运行 Seed 方法。再看我们的数据库,已经把主键全都变成了int
相关文档资料
http://www.asp.net/identity
http://typecastexception.com/post/2014/07/13/ASPNET-Identity-20-Extending-Identity-Models-and-Using-Integer-Keys-Instead-of-Strings.aspx
转载请标明出处:http://giantliu.com
扩展ASP.NET Identity使用Int做主键的更多相关文章
- 使用Guid做主键和int做主键性能比较
使用Guid做主键和int做主键性能比较 在数据库的设计中我们常常用Guid或int来做主键,根据所学的知识一直感觉int做主键效率要高,但没有做仔细的测试无法 说明道理.碰巧今天在数据库的优化过程中 ...
- mysql5.5 uuid做主键与int做主键的性能实测
数据库:mysql5.5 表类型:InnoDB 数据量:100W条 第一种情况: 主键采用uuid 32位. 运行查询语句1:SELECT COUNT(id) FROM test_varchar; 运 ...
- int 和guid做主键的时候性能的区别
1.在经常需要做数据迁移的系统中,建议用Guid.并且在相应的外键字段,也就是用来做连接查询的字段添加非聚集索引,对于改善性能有极大的好处.where条件的字段也可以适当添加非聚集索引. 2.在使用G ...
- 从Membership 到 .NET4.5 之 ASP.NET Identity
我们前面已经讨论过了如何在一个网站中集成最基本的Membership功能,然后深入学习了Membership的架构设计.正所谓从实践从来,到实践从去,在我们把Membership的结构吃透之后,我们要 ...
- [转]Membership 到 .NET4.5 之 ASP.NET Identity
本文转自:http://www.cnblogs.com/jesse2013/p/membership-part3.html 我们前面已经讨论过了如何在一个网站中集成最基本的Membership功能,然 ...
- 【ASP.NET Identity系列教程(三)】Identity高级技术
注:本文是[ASP.NET Identity系列教程]的第三篇.本系列教程详细.完整.深入地介绍了微软的ASP.NET Identity技术,描述了如何运用ASP.NET Identity实现应用程序 ...
- (转)从Membership 到 .NET4.5 之 ASP.NET Identity
引入 - 用户信息是如何存在数据库中的 我们前两篇都只讲到了怎么用Membership注册,登录等,但是我们漏掉了一个很重要并且是基本上每个用Membership的人都想问的,我的用户信息怎么保存?我 ...
- ASP.NET Identity 三(转载)
转载来源:http://www.cnblogs.com/r01cn/p/5194257.html 注:本文是[ASP.NET Identity系列教程]的第三篇.本系列教程详细.完整.深入地介绍了微软 ...
- ASP.NET Identity系列教程-4【Identity高级技术】
https://www.cnblogs.com/r01cn/p/5194257.html 15 ASP.NET Identity高级技术 In this chapter, I finish my de ...
随机推荐
- (后端)java回调机制
转自强哥: 所谓回调,就是客户程序C调用服务程序S中的某个函数A,然后S又在某个时候反过来调用C中的某个函数B,对于C来说,这个B便叫做回调函数.例如Win32下的窗口过程函数就是一个典型的回调函数. ...
- JavaScript大杂烩13 - 总结ECMAScript 5新功能
虽说这个标准已经出来很久了,所有的主流浏览器的最新版本也都支持了这些特性,但是很多的教程中并没有包含这个部分,这一节我们专门来总结一下这个标准中的新功能. Object的新方法 在最新的JavaScr ...
- 使用wxpy来实现自动发送消息统计微信好友信息的功能
发送消息太频繁会出现禁言消息 1:导入wxpy模块 pip install wxpy pip3 install wxpy #二者选一 调用模块 # 导入模块 from wxpy import * # ...
- Mac命令行使用tree查看目录结构
默认tree命令是无法使用的,可以使用homebrew install tree安装. 如果直接使用tree,查看的目录里面含有中文字符的目录或文件时会出现汉字不能显示的问题,可以使用tree -N查 ...
- IDEA 编译 Jmeter 5.0(二次开发)
windows10 操作系统,jdk1.8,Intellij IDEA 2018,jmeter5.0 1.下载 http://jmeter.apache.org/download_jmeter.cgi ...
- luogu P2000 拯救世界
嘟嘟嘟 题目有点坑,要你求的多少大阵指的是召唤kkk的大阵数 * lzn的大阵数,不是相加. 看到这个限制条件,显然要用生成函数推一推. 比如第一个条件"金神石的块数必须是6的倍数" ...
- win10下SVN图标不显示
win10系统的SVN图标不现实了.正常情况下,会在文件夹上有一个对勾 但是对勾以及所有的SVN图标都突然消失了,都不知道文件什么状态了. 经过一通搜索,发现问题所在(都指向注册表图标被占用).原因就 ...
- mysql获取表中数据行数
获取单个表的行数 使用count(*)或者count(1) SELECT count(1) AS count FROM table_name; 执行结果 获取两个表的行数 使用union组合每个sel ...
- TStack与IBM LinuxONE通过兼容性认证
近日,腾讯云TStack与IBM LinuxONE通过兼容性认证,通过腾讯云TStack,可实现便捷管理IBM LinuxONE服务器.这为腾讯和IBM在未来多方面的商业合作奠定了坚实基础,也为腾讯云 ...
- PAT A1136 A Delayed Palindrome (20 分)——回文,大整数
Consider a positive integer N written in standard notation with k+1 digits ai as ak⋯a1a0 ...

