如何做到这一点的功劳可以在这个链接https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x的cmets中找到
将 ApplicationUser 更改为从 IdentityUser 继承
创建一个继承自 IdentityRole 的新类 ApplicationRole
将 ApplicationDbContext 更改为继承自 IdentityDbContext<ApplicationUser, ApplicationRole, int>
将 services.AddIdentity 的 startup.cs 更改为使用 ApplicationRole
更改 UrlHelperExtensions 方法以在签名中使用带有 T userId 的通用
将 ManageController 的 LinkLoginCallback 调用改为
await _signInManager.GetExternalLoginInfoAsync(user.Id.ToString())
将以下行添加到 ApplicationDbContext OnModelCreating 方法(在 base.OnModelCreating 调用之后)
builder.Entity<ApplicationUser>().Property(p => p.Id).UseSqlServerIdentityColumn();
如果使用Guid,则替换
builder.Entity<ApplicationUser>().Property(p => p.Id).UseSqlServerIdentityColumn();
与
builder.Entity<ApplicationUser>().Property(p => p.Id).ValueGeneratedOnAdd();
所有更改如下
public class ApplicationUser : IdentityUser<Guid>
{
}
public class ApplicationRole : IdentityRole<Guid>
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
{
Public ApplicationDbContext(DbContextOptions < ApplicationDbContext > Options): Base (Options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
// For Guid Primary Key
builder.Entity<ApplicationUser>().Property(p => p.Id).ValueGeneratedOnAdd();
// For int Primary Key
//builder.Entity<ApplicationUser>().Property(p => p.Id).UseSqlServerIdentityColumn();
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
}
public static class UrlHelperExtensions
{
public static string EmailConfirmationLink<T>(this IUrlHelper urlHelper, T userId, string code, string scheme)
{
return urlHelper.Action(
action: nameof(AccountController.ConfirmEmail),
controller: "Account",
values: new { userId, code },
protocol: scheme);
}
public static string ResetPasswordCallbackLink<T>(this IUrlHelper urlHelper, T userId, string code, string scheme)
{
return urlHelper.Action(
action: nameof(AccountController.ResetPassword),
controller: "Account",
values: new { userId, code },
protocol: scheme);
}
}
....
var info = await _signInManager.GetExternalLoginInfoAsync(user.Id.ToString());