2017-02-02 10 views
7

Önce Entity Framework 6 ile Asp.net'de bir web uygulaması ve veritabanı var. o connect.Here benim koduna kullanıcı için geldiğimde sorunu yaşıyorum:varlık türü ApplicationUser geçerli içerik için modelin bir parçası değil

Web.config

<connectionStrings> 
    <add name="DefaultConnection" connectionString="data source=MyServer\MyDataBase;initial catalog=Cliniciel_WebRV_Master;User Id=XXX;Password=XXXX" providerName="System.Data.SqlClient" /> 
    <add name="Cliniciel_WebRV_MasterEntities" connectionString="metadata=res://*/Models.Entities.Cliniciel_WebRV_Master.csdl|res://*/Models.Entities.Cliniciel_WebRV_Master.ssdl|res://*/Models.Entities.Cliniciel_WebRV_Master.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MyServer\MyDataBase;initial catalog=Cliniciel_WebRV_Master;user id=XXX;password=XXXX;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> 
    <add name="Cliniciel_WebRV_Entities" connectionString="metadata=res://*/Models.Entities.Cliniciel_WebRV_Entities.csdl|res://*/Models.Entities.Cliniciel_WebRV_Entities.ssdl|res://*/Models.Entities.Cliniciel_WebRV_Entities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MyServer\MyDataBase;initial catalog=Cliniciel_WebRV_DEV;user id=XXX;password=XXXX;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> 
    <add name="Cliniciel_WebRV_Oauth" connectionString="metadata=res://*/Models.Entities.Cliniciel_WebRV_Oauth.csdl|res://*/Models.Entities.Cliniciel_WebRV_Oauth.ssdl|res://*/Models.Entities.Cliniciel_WebRV_Oauth.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MyServer\MyDataBase;initial catalog=Cliniciel_WebRV_Master;user id=XXX;password=XXXX;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />   
</connectionStrings> 

İşte benim kimlik doğrulama için bağlantı dizesini "Cliniciel_WebRV_Oauth" kullanırlar.

Ben

Startup.cs başlangıçta

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>(ApplicationUserManager.Create); 

      //app.CreatePerOwinContext<ApplicationRoleManager>(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 benim oauthToken yapılandırmak

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<ApplicationUser> //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<object>(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<ApplicationUserManager>(); 

       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); 
       } 

     } 
    } 
} 

İşte ben var hatadır:

ApplicationUser varlık türü geçerli bağlam için modelin bir parçası değildir.

Ligne 32: burada

iz var var UserManager = context.OwinContext.GetUserManager(); Ligne 33 : Ligne 34: ApplicationUser kullanıcısı = userManager.FindAsync (context.UserName, context.Password) bekleniyor; Ligne 35: ligne 36: Eğer (kullanım == null)

Fichier kaynağı: C: ​​\ Kullanıcılar \ aboucher \ Masaüstü \ WebRV-2016/05/12 - Copie \ Cliniciel_WebRV \ WebRV \ WebRV Sağlayıcılar \ \ CustomOAuthProvider .cs
Ligne: 34

İz de la kazık:

[ınvalidoperationexception: Le tipi d'Entite ApplicationUser ne fait pas partie du modèle le contexte actuel dökün.]
System.Data.Entity. Internal.InternalContext.UpdateEntitySetMappingsForType (Tür EntityType) +4479799
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType (Tip EntityType) 37
System.Data.Entity.Internal.Linq.InternalSet 1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet
1.get_InternalContext() 16 System.Data .Entity.Infrastructure.DbQuery kaynak Expression kaynak Expression 1 predicate) +163
Microsoft.AspNet.Identity.EntityFramework.<GetUserAggregateAsync>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.<FindAsync>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() c: \ Users \ aboucher \ Desktop \ WebRV-2016-05-12 - Copie \ Cliniciel_WebRV \ WebRV \ WebRV \ Sağlayıcılar \ CustomOAuthProvider.cs: 34 Sistem.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (Görev görev) 92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (Görev görev) 58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() 26 Microsoft.Owin. Security.OAuth.d__3f.MoveNext() 863 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (görev görev) 92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (görev görev) 58 System.Runtime. CompilerServices.TaskAwaiter 1.GetResult() +28 Microsoft.Owin.Security.OAuth.<InvokeTokenEndpointAsync>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.<InvokeAsync>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.TaskAwai ter.ThrowForNonSuccess (Görev görev) 92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (Görev görev) 58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() 26 Microsoft.AspNet.Identity.Owin. d__0.MoveNext() 641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (görev görev) 92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (görev görev) 58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 Microsoft.AspNet.Identity.Owin.d__0.MoveNext() +641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (Görev görev) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (Görev görev) 58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() 26 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext() 287 Sistem .Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (görev görev) 92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (görev görev) 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 (ıasyncresult ar) + 150
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork (ıasyncresult ar) +42
System.Web.AsyncEventExecutionStep .System.Web.HttpApplication.IExecutionStep.Execute() 380 System.Web.HttpApplication.ExecuteStep (IExecutionStep step, Boolean & completedSynchronously) +155

+0

İngilizce'ye o hata mesajı çevirmek ve içine metin olarak yayınlamayın lütfen bu satırı yazmaktır soru; Bu şekilde daha fazla yardım alırsınız. – Alex

+0

@Alex Şimdi daha açık mı? – alexandre

+0

Daha iyi. Ayrıca istisna atar satır da dahil. – Alex

cevap

4

nerede ApplicationUserManager Yöntem

size DBContext

ileterek bu gibi uygulama UserManager yapılandırmanız gerekir
public class ApplicationUserManager : UserManager<ApplicationUser> 
{ 
    public ApplicationUserManager(IUserStore<ApplicationUser> store) 
     : base(store) 
    { 
    } 

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    { 
     var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<EducationContext>())); 
     // Configure validation logic for usernames 
     manager.UserValidator = new UserValidator<ApplicationUser>(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<ApplicationUser> 
     { 
      MessageFormat = "Your security code is {0}" 
     }); 
     manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser> 
     { 
      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<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity")); 
     } 
     return manager; 
    } 
} 

en önemli (İlk Satır yöntemi oluşturma)

var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<EducationContext>())); 
İlgili konular