实体类型ApplicationUser不是当前上下文的模型的一部分

我在Asp.net中有一个带有Entity Framework 6和数据库的Web应用程序。 当用户连接时,我遇到了问题。这是我的代码:

Web.config文件

      

在这里,我使用连接字符串“Cliniciel_WebRV_Oauth”进行身份validation。

我在启动时配置我的oauthToken

Startup.cs

  private void ConfigureOAuthTokenGeneration(IAppBuilder app) { //// Configure the db context and user manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext(ApplicationUserManager.Create); //app.CreatePerOwinContext(ApplicationRoleManager.Create); OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { //For Dev enviroment only (on production should be AllowInsecureHttp = false) #if DEBUG AllowInsecureHttp = true, #endif TokenEndpointPath = new PathString("/oauth/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new CustomOAuthProvider(), AccessTokenFormat = new CustomJwtFormat("http://localhost:55555/") }; // OAuth 2.0 Bearer Access Token Generation app.UseOAuthAuthorizationServer(OAuthServerOptions); } private void ConfigureOAuthTokenConsumption(IAppBuilder app) { var issuer = "http://localhost:55555/"; string audienceId = ConfigurationManager.AppSettings["as:AudienceId"]; byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]); // Api controllers with an [Authorize] attribute will be validated with JWT app.UseJwtBearerAuthentication( new JwtBearerAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active, AllowedAudiences = new[] { audienceId }, IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] { new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret) } }); } 

ApplicationDBContext.cs

 using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Linq; using System.Web; using System.Web.Services; using System.Web.SessionState; using WebRV.Models.Entities; namespace WebRV.Infrastructure { public class ApplicationDbContext : IdentityDbContext //DOIT CREER APPLICATION USER. { public ApplicationDbContext() : base("Cliniciel_WebRV_Oauth", throwIfV1Schema: false) { Configuration.ProxyCreationEnabled = false; Configuration.LazyLoadingEnabled = false; } [WebMethod(EnableSession = true)] public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } } 

CustomOAuthProvider.cs

 using System; using System.Linq; using WebRV.Infrastructure; using Microsoft.Owin.Security; using Microsoft.Owin.Security.OAuth; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity.Owin; using System.Web.Mvc; using WebRV.Models.Entities; using System.Net; using System.Web.Http; namespace WebRV.Providers { public class CustomOAuthProvider : OAuthAuthorizationServerProvider { [ValidateAntiForgeryToken] public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { context.Validated(); return Task.FromResult(null); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var allowedOrigin = "*"; context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var userManager = context.OwinContext.GetUserManager(); ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); } else { //if (!user.EmailConfirmed) //{ // context.SetError("invalid_grant", "User did not confirm email."); // return; //} ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); var ticket = new AuthenticationTicket(oAuthIdentity, null); context.Validated(ticket); } } } } 

这是我得到的错误:

ApplicationUser实体类型不是当前上下文的模型的一部分。

这是跟踪:

Ligne 32:var userManager = context.OwinContext.GetUserManager(); Ligne 33:Ligne 34:ApplicationUser user = await userManager.FindAsync(context.UserName,context.Password); Ligne 35:Ligne 36:if(user == null)

Fichier来源:c:\ Users \ aboucher \ Desktop \ WebRV-2016-05-12 – Copie \ Cliniciel_WebRV \ WebRV \ WebRV \ Providers \ CustomOAuthProvider.cs
Ligne:34

Trace de la pile:

[InvalidOperationException:Le type d’entitéApplicationUserne fait pas partiedumodèlepourle contexte actuel。]
System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type entityType)+4479799
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)+37
System.Data.Entity.Internal.Linq.InternalSet 1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet
1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet
1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet
1.get_InternalContext()+ 16 System.Data.Entity.Infrastructure.DbQuery 1.System.Linq.IQueryable.get_Provider() +39 System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable ()+ 1.System.Linq.IQueryable.get_Provider() +39 System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable 1 source,Expression 1 predicate, CancellationToken cancellationToken) +154 System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable 1 source,Expression 1 predicate) +163
Microsoft.AspNet.Identity.EntityFramework.d__6c.MoveNext() +807 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter
1 predicate) +163
Microsoft.AspNet.Identity.EntityFramework.d__6c.MoveNext() +807 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter
1 predicate) +163
Microsoft.AspNet.Identity.EntityFramework.d__6c.MoveNext() +807 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter
1.GetResult()+28 Microsoft.AspNet.Identity.CultureAwaiter 1.GetResult() +123 Microsoft.AspNet.Identity.d__12.MoveNext() +601
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter
+ 1.GetResult() +123 Microsoft.AspNet.Identity.d__12.MoveNext() +601
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter
1.GetResult() +123 Microsoft.AspNet.Identity.d__12.MoveNext() +601
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter
1.GetResult() +123 Microsoft.AspNet.Identity.d__12.MoveNext() +601
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter
1.GetResult()+ 28 WebRV.Providers.d__0.MoveNext()in c:\ Users \ aboucher \ Desktop \ WebRV- 2016-05-12 – Copie \ Cliniciel_WebRV \ WebRV \ WebRV \ Providers \ CustomOAuthProvider.cs:34 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)+92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)+58 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+26 Microsoft.Owin.Security.OAuth.d__3f.MoveNext()+863 System.Runtime.CompilerServices.TaskAwaiter .ThrowForNonSuccess(任务任务)+92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)+58 System.Runtime.CompilerServices.TaskAwaiter 1.GetResult() +28 Microsoft.Owin.Security.OAuth.d__22.MoveNext() +2336 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 Microsoft.Owin.Security.OAuth.d__0.MoveNext() +1733 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter
1.GetResult() +28 Microsoft.Owin.Security.OAuth.d__22.MoveNext() +2336 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 Microsoft.Owin.Security.OAuth.d__0.MoveNext() +1733 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter
1.GetResult() +28 Microsoft.Owin.Security.OAuth.d__22.MoveNext() +2336 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 Microsoft.Owin.Security.OAuth.d__0.MoveNext() +1733 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter
1.GetResult()+28 Microsoft.Owin.Security.Infrastructure.d__0.MoveNext()+ 664 System.Runtime.CompilerServices。 TaskAwaiter.ThrowForNonSuccess(任务任务)+92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)+58 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+26 Microsoft.AspNet.Identity.Owin.d__0.MoveNext()+641 System.Runtime.CompilerServices.TaskAwaiter .ThrowForNonSuccess(任务任务)+92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)+58 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+26 Microsoft.AspNet.Identity.Owin.d__0.MoveNext()+641 System.Runtime.CompilerServices.TaskAwaiter .ThrowForNonSuccess(任务任务)+92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)+58 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+26 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext()+287 System.Runtime.CompilerServices .TaskAwaiter.ThrowForNonSuccess(任务任务)+92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)+58 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+26 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__2.MoveNext()+272 System.Runtime.ExceptionServices .ExceptionDispatchInfo.Throw()+26 Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow()+33 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar)+150
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)+42
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()+380 System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&completedSynchronously)+155

ApplicationUserManager方法在哪里?

您需要通过传递DbContext来配置应用程序UserManager

 public class ApplicationUserManager : UserManager { public ApplicationUserManager(IUserStore store) : base(store) { } public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context) { var manager = new ApplicationUserManager(new UserStore(context.Get())); // Configure validation logic for usernames manager.UserValidator = new UserValidator(manager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords manager.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, }; // Configure user lockout defaults manager.UserLockoutEnabledByDefault = true; manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); manager.MaxFailedAccessAttemptsBeforeLockout = 5; // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user // You can write your own provider and plug it in here. manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider { MessageFormat = "Your security code is {0}" }); manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider { Subject = "Security Code", BodyFormat = "Your security code is {0}" }); manager.EmailService = new EmailService(); manager.SmsService = new SmsService(); var dataProtectionProvider = options.DataProtectionProvider; if (dataProtectionProvider != null) { manager.UserTokenProvider = new DataProtectorTokenProvider(dataProtectionProvider.Create("ASP.NET Identity")); } return manager; } } 

最重要的是写这一行(Create方法中的第一行)

 var manager = new ApplicationUserManager(new UserStore(context.Get()));