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

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

我正在将 Identity Server 3 与 mysql 一起使用,因此我定义了 mysql 连接字符串,并且登录工作了几次,之后它停止工作,并且我从 Identity Server 收到错误。部署到 azure 后会发生这种情况。

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

进一步查看,我可以看到 EF 无法连接到 mysql。我尝试重述 azure 网站,但没有成功。所以我查看了我的 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
}

关于c# - Identity Server 3 - Entity Framework 在几次成功登录后停止连接到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45845322/

相关文章:

c# - 工作单元和存储库模式

php - MySQL请求按公共(public)值排序

php - 使用锁表时事务+回滚

asp.net-mvc - 续订 Azure ACS 颁发的 JWT

c# - 类关键字 - 显式指示继承接口(interface)?

c# - 以编程方式抑制 Windows 警报

c# - 使用委托(delegate)表示法访问通用列表

php - 如何使用 PHP 将 MySQL 时间转换为 ISO 8601 持续时间

azure - 禁用存储帐户的加密

azure - 构建、分析和崩溃报告 - App Center 或 Azure