繁体   English   中英

Identity Server 3-几次成功登录后,Entity Framework停止连接到MySQL

[英]Identity Server 3 - Entity Framework stops connecting to MySQL after few successful login

我将Identity Server 3与mysql一起使用,因此我定义了mysql连接字符串,并且登录有效了几次,然后登录停止工作,并且我从Identity Server中收到错误消息。 部署到天蓝色后会发生这种情况。

请注意,我的连接字符串没有问题,因为它适用于前几次登录。

再往前看,我可以看到EF无法连接到mysql。 我曾尝试过重塑天蓝色的网站,但没有运气。 因此,我查看了我的mysql服务器,并在客户端连接列表中看到了来自azure IP的空闲连接。 我使用MYSQL工作台手动停止了连接,然后再次开始工作。 但是在几次成功登录后,问题仍然存在。

这是我在跟踪文件中看到的错误

Unhandled exception accessing: /identity/login
System.Data.Entity.Core.ProviderIncompatibleException: An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure. ---> System.Data.Entity.Core.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> MySql.Data.MySqlClient.MySqlException: Unable to connect to any of the specified MySQL hosts.
   at MySql.Data.MySqlClient.NativeDriver.Open()
   at MySql.Data.MySqlClient.Driver.Open()
   at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
   at MySql.Data.MySqlClient.MySqlPool.CreateNewPooledConnection()
   at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
   at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
   at MySql.Data.MySqlClient.MySqlPool.GetConnection()
   at MySql.Data.MySqlClient.MySqlConnection.Open()
   at MySql.Data.MySqlClient.MySqlProviderServices.GetDbProviderManifestToken(DbConnection connection)
   at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
   --- End of inner exception stack trace ---
   at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
   at System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
   --- End of inner exception stack trace ---
   at System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
   at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.<>c__DisplayClass1.<ResolveManifestToken>b__0(Tuple`3 k)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.ResolveManifestToken(DbConnection connection)
   at System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest)
   at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
   at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
   at System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable`1 source, Expression`1 predicate, CancellationToken cancellationToken)
   at System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable`1 source, Expression`1 predicate)
   at Microsoft.AspNet.Identity.EntityFramework.UserStore`6.<GetUserAggregateAsync>d__6c.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at IdentityServer3.AspNetIdentity.AspNetIdentityUserService`2.<FindUserAsync>d__19.MoveNext() in F:\VSO\Porto.la\Portola API\Portola.IdentityServer\App_Packages\IdentityServer3.AspNetIdentity\IdentityServer3.AspNetIdentity.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at IdentityServer3.AspNetIdentity.AspNetIdentityUserService`2.<AuthenticateLocalAsync>d__21.MoveNext() in F:\VSO\Porto.la\Portola API\Portola.IdentityServer\App_Packages\IdentityServer3.AspNetIdentity\IdentityServer3.AspNetIdentity.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at IdentityServer3.Core.Endpoints.AuthenticationController.<LoginLocal>d__9.MoveNext() in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Endpoints\AuthenticationController.cs:line 234
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Threading.Tasks.System.Web.Http910911.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext() in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Configuration\Hosting\NoCacheAttribute.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext() in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Configuration\Hosting\NoCacheAttribute.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext() in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Configuration\Hosting\NoCacheAttribute.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext() in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Configuration\Hosting\NoCacheAttribute.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext() in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Configuration\Hosting\NoCacheAttribute.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext() in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Configuration\Hosting\NoCacheAttribute.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext() in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Configuration\Hosting\NoCacheAttribute.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext() in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Configuration\Hosting\NoCacheAttribute.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Configuration\Hosting\NoCacheAttribute.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext() in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Configuration\Hosting\NoCacheAttribute.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext() in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Configuration\Hosting\NoCacheAttribute.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__0.MoveNext() in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Configuration\Hosting\NoCacheAttribute.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext() in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Configuration\Hosting\NoCacheAttribute.cs:line 0

下面是与asp.net身份相关的类

public class CustomIdentityDbContext : IdentityDbContext<CustomIdentityUser>
{
    public CustomIdentityDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

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

public class CustomIdentityUser : IdentityUser
{
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
}

public class CustomUserStore : UserStore<CustomIdentityUser>
{
    public CustomUserStore(DbContext ctx)
       : base(ctx)
    {
    }
}

public class CustomUserManager : UserManager<CustomIdentityUser>
{
    public CustomUserManager(IUserStore<CustomIdentityUser> store)
        : base(store)
    {
    }
public static CustomUserManager Create(IdentityFactoryOptions<CustomUserManager> options, IOwinContext context)
{
    var manager = new CustomUserManager(new CustomUserStore(context.Get<CustomIdentityDbContext>()));
    // Configure validation logic for usernames
    manager.UserValidator = new UserValidator<CustomIdentityUser>(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<CustomIdentityUser>
    {
        MessageFormat = "Your security code is {0}"
    });
    manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<CustomIdentityUser>
    {
        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<CustomIdentityUser>(dataProtectionProvider.Create("ASP.NET Identity"));
    }
    return manager;
}
}

以下是身份服务器3的配置

 app.Map(
                "/identity",
                coreApp =>
                    {
                        var factory =
                            new IdentityServerServiceFactory()
                                .UseInMemoryClients(Clients.Get())
                                .UseInMemoryScopes(Scopes.Get());
                        factory.ViewService = new Registration<IViewService, IdentityCustomViewService>();

                        factory.Register(new Registration<CustomIdentityDbContext>());
                        factory.Register(new Registration<UserStore<CustomIdentityUser>>(x => new CustomUserStore(x.Resolve<CustomIdentityDbContext>())));
                        factory.Register(new Registration<UserManager<CustomIdentityUser, string>>(x => new CustomUserManager(x.Resolve<UserStore<CustomIdentityUser>>())));
                        factory.UserService = new Registration<IUserService, AspNetIdentityUserService<CustomIdentityUser, string>>();

                        coreApp.UseIdentityServer(
                            new IdentityServerOptions
                            {
                                SiteName = "Identity Server",
                                SigningCertificate = Cert.Load(),
                                Factory = factory,
                                RequireSsl = true,
                                AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions
                                {
                                    EnablePostSignOutAutoRedirect = true,
                                }
                            });

                    });

请检查您的代码,并确保在处理完数据库上下文后已将其释放。 否则将耗尽连接池,并且您可能无法获得连接。 您可以使用using语句来实现。 以下代码供您参考。

using (var dbContext = new YourMySqlDbContext())
{
    //do something with your dbContext
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM