1

我在我的解決方案,域,API和Web中有3個項目。最近我更新了Asp.net Identity form 1.0到2.0。一切工作正常在我的Web項目,但是當我嘗試在網絡API項目獲得令牌,我得到這個錯誤(從1.0到2.0的一切升級Identity工作過):Asp.net身份2實體類型用戶不是當前上下文的模型的一部分

The entity type User is not part of the model for the current context 

我的User類看起來是這樣的:

public class User : IdentityUser 
{ 
    //more code here 
} 

這裏是我的數據庫上下文類:

public class DatabaseContext : IdentityDbContext<User> 
     { 
      public DatabaseContext() 
       : base("DefaultConnection", throwIfV1Schema: false) 
      { 
       Configuration.LazyLoadingEnabled = true; 
      } 

      //more code here 

     protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 

      base.OnModelCreating(modelBuilder); 
      modelBuilder.Entity<IdentityUser>() 
       .ToTable("AspNetUsers"); 
      modelBuilder.Entity<User>() 
       .ToTable("AspNetUsers"); 
     } 

    } 

在我的Web API項目,我已經更換了所有引用從IdentityUser到用戶,例如方法獲得令牌看起來像:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
    { 
     using (UserManager<User> userManager = _userManagerFactory()) 
     { 
      var user = userManager.Find(context.UserName, context.Password); 

      if (user == null) 
      { 
       context.SetError("invalid_grant", "The user name or password is incorrect."); 
       return; 
      } 

      ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user, 
       context.Options.AuthenticationType); 
      ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user, 
       CookieAuthenticationDefaults.AuthenticationType); 
      AuthenticationProperties properties = CreateProperties(user.UserName); 
      AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); 
      context.Validated(ticket); 
      context.Request.Context.Authentication.SignIn(cookiesIdentity); 
     } 
    } 

我該如何解決這個問題?

+0

我認爲IdentityDbContext對於給定的用戶類型,所以我不知道這是正確的創建DbSet - 但嘗試'modelBuilder.Entity ()...''而不是'modelBuilder.Entity ()...' –

+0

我有兩個,但我刪除了modelBuilder.Entity (),只剩下modelBuilder.Entity (),但它沒有幫助 – hyperN

回答

1

我已經固定它,

所以,問題與更新Asp.net身份從1.0到2.0的ASP.net的Web API處理事情有些不同了2.0所以我所做的就是:

  1. 更新VS 2013(更新2)
  2. 創建新的Web API 2項目的另一種解決方案,並與我的Web API項目
    進行了比較,並添加缺少的類它(只是複製/粘貼)
  3. 我的DatabaseContext類我已經添加了方法:

    public static DatabaseContext Create() { return new DatabaseContext(); }

  4. 和我的用戶等級:

    公共異步任務GenerateUserIdentityAsync(經理的UserManager,串authenticationType) {// 注意authenticationType必須CookieAuthenticationOptions.AuthenticationType定義的一個 VAR的UserIdentity =等待匹配manager.CreateIdentityAsync(this,authenticationType); //在此處添加自定義用戶聲明 return userIdentity; }

  5. 我已經改變了在網絡API項目中的所有ApplicationUser引用我的用戶參考
相關問題