尝试在 ASP.NET Core 2.0中实现Identity。 有很多问题让我解决这个问题。
启动.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("Ctrack6_Custom"))
);
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
etc...
应用程序用户.cs使用 Guid 作为键。 还设置在角色等
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser<Guid>
{
[MaxLength(50)]
public string FirstName { get; set; }
[MaxLength(50)]
public string LastName { get; set; }
[MaxLength(5)]
public string OrgCode { get; set; }
public ApplicationUser() : base()
{
}
}
ApplicationDbContext.cs 在类定义上此文件中引发错误。 ApplicationDbContext 引发此错误:
类型"App.Identity.ApplicationUser"不能用作泛型类型或方法"IdentityDbContext"中的类型参数"TUser"。没有从"App.Identity.ApplicationUser"到"Microsoft.AspNetCore.Identity.IdentityUser"的隐式引用转换。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
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);
builder.Entity<blah>()
.HasKey(c => new { fields, for, key });
}
public DbSet<etc> Etcs {get; set; }
}
更改public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
自
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
您需要有一个类似于 ApplicationUser 类的 ApplicationRole 类。据我所知,一旦您指定了密钥类型(在本例中为 Guid,默认为字符串(,即使您不使用角色,您也需要包含角色和密钥类型。
这就是对我有用的:
public class DataContext : IdentityDbContext<ApplicationUser,IdentityRole<Guid>,Guid>
我遇到了这个问题,终于意识到这是因为我愚蠢的错误。 确保 IdentityUser 派生自包 Microsoft.AspNetCore.Identity 而不是 Microsoft.AspNet.Identity.Core<</em>
我通过意外删除应用程序用户的类定义中的继承而得到同样的错误:
public class ApplicationUser : IdentityUser
{
...
}