Identity Server 3 - 实体框架在几次成功登录后停止连接到MySQL

时间:2017-08-23 16:49:10

标签: c# mysql azure entity-framework-6 identity

我正在使用带有mysql的Identity Server 3,所以我定义了mysql连接字符串,登录工作了几次,然后它停止工作,我从Identity Server收到错误。在部署到azure之后会发生这种情况。

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

进一步观察我可以看到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,
                                }
                            });

                    });

1 个答案:

答案 0 :(得分:0)

请检查您的代码并确保在完成后处理了数据库上下文。不这样做将耗尽您的连接池,您可能无法获得连接。你可以用using语句来做。以下代码供您参考。

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