【问题标题】:Migrating Identity in .net core 2 class library在 .net core 2 类库中迁移身份
【发布时间】:2017-10-21 21:56:15
【问题描述】:

我一直在尝试将带有 Identity 的类库添加到 .net core 2 项目中。

项目Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddIdentity<MyDbContext, IdentityRole>()
            .AddEntityFrameworkStores<MyDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseAuthentication();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
   }

类库:

namespace MSContext
{
    public class MyDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
    {
        public MyDbContext CreateDbContext(string[] args)
        {
            var builder = new DbContextOptionsBuilder<MyDbContext>();
            builder.UseSqlServer(connectionString);
            return new MyDbContext(builder.Options);
        }
    }

    public class MyDbContext: IdentityDbContext<ApplicationUser>
    {
        public MyDbContext(DbContextOptions<MyDbContext> options)
            : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(connectionString);
        }




        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

        }
}

类库ApplicationUser.cs:

public class ApplicationUser : IdentityUser
{

}

当我尝试迁移时使用:Add-Migration

我收到此错误:

在类上调用方法“BuildWebHost”时发生错误 '程序'。在没有应用程序服务提供商的情况下继续。错误: AddEntityFrameworkStores 只能由派生的用户调用 来自身份用户。

当我搜索此错误时,我不断收到有关自定义身份模型的问题,但这不是我的情况。我只是想按原样迁移它。我错过了什么?

【问题讨论】:

  • 看起来您的 ApplicationUser 没有从 IdentityUser 继承。您可以添加您的 ApplicationUser 的代码吗?
  • @Nikolaus 我已经添加了文件。它只是自动添加到项目中的基本空类。
  • 你能在你的 ApplicationUser.cs 和你的上下文文件中添加使用吗?
  • @Nikolaus 使用是什么意思?这只是我在以任何方式使用上下文之前尝试迁移的基础。
  • 我的意思是 .cs 文件顶部的 using 语句,例如 using System;

标签: asp.net-identity class-library asp.net-core-2.0


【解决方案1】:

发现问题。我用错了AddIdentity&lt;&gt;。 应该使用ApplicationUser 而不是MyDbContext。 这是修正版:

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<MyDbContext>()
        .AddDefaultTokenProviders(); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多