【问题标题】:use asp .net identity user in another project在另一个项目中使用 asp .net 身份用户
【发布时间】:2018-06-17 06:58:52
【问题描述】:

我有 2 个项目,其中一个是 asp web api,另一个是类库,例如数据访问层,我还有两个实体框架上下文。 我在 web api 项目中使用 web api 的 ApiUser。

这是我在 webApi 项目中的 ApiUser:

public class ApiUser : IdentityUser
{
    public int? OrganizationId { get; set; }
    public string Name { get; internal set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApiUser> manager, string authenticationType)
    {
        CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
        return userIdentity;
    }
}

这是我在 web api 项目中的 dbContext:

public class ApiDbContext : IdentityDbContext<ApiUser>
{
    public ApiDbContext()
        : base("PelicanConnection", throwIfV1Schema: false)
    {
    }

    public static ApiDbContext Create()

    {
        return new ApiDbContext();
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<ApiUser>().ToTable("ApiUsers");
        modelBuilder.Entity<IdentityRole>().ToTable("ApiRoles");
        modelBuilder.Entity<IdentityUserRole>().ToTable("ApiUserRoles");
        modelBuilder.Entity<IdentityUserClaim>().ToTable("ApiUserClaims");
        modelBuilder.Entity<IdentityUserLogin>().ToTable("ApiUserLogins");


    }
}

这是我在数据访问项目中的上下文:

 public class AppContext : DbContext
{
    public AppContext() : base("AppConnection")
    {
        this.Configuration.LazyLoadingEnabled = false;

    }

    public DbSet<ApiUser> ApiUsers { get; set; }
    public DbSet<Reception> Receptions { get; set; }
    public DbSet<Box> Boxes { get; set; }


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Ignore<ApiUser>();
    }
}

为了在两个项目中使用 ApiUser,我不得不在数据访问项目上下文中忽略 ApiUser。 如何在数据访问上下文中访问 ApiUser DbSet?

【问题讨论】:

    标签: c# asp.net-web-api entity-framework-6 asp.net-identity dbcontext


    【解决方案1】:

    您可以在类对象前面添加namespace,以便编译器知道使用哪一个,无需忽略。您可以尝试将这两个对象相互转换。

    你应该看看Dependancy Injection是如何解决这个问题的,例如你可以创建一个Interface来描述ApiUser、IApiUser,并让两个不同的ApiUser类继承这个接口。

    https://www.dotnettricks.com/learn/dependencyinjection/implementation-of-dependency-injection-pattern-in-csharp

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-30
      • 2019-07-20
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多