【问题标题】:Configuration Store is Disposed配置存储已处置
【发布时间】:2019-05-07 17:05:06
【问题描述】:

ConfigurationDbContext 在生成令牌之前被释放。使用 IdentityServerTools 时。我已经尝试过手动添加 ConfigurationDbContext 和依赖配置存储中的配置

在我的 Startup.cs 中,我已经像这样配置了 IdentityServer:

//I've also tried without this line
services.AddDbContext<ConfigurationDbContext>(options 
    => options.UseSqlServer(connectionString));

var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddIdentityServer()
   .AddDeveloperSigningCredential()
   .AddAspNetIdentity<ApplicationUser>()
   .AddOperationalStore(options =>
   {
       options.ConfigureDbContext = builder =>
           builder.UseSqlServer(connectionString,
            s => s.MigrationsAssembly(migrationsAssembly));

        // this enables automatic token cleanup. this is optional.
        options.EnableTokenCleanup = true;
        options.TokenCleanupInterval = 30;
   })
   .AddConfigurationStore(options =>
   {
      options.ConfigureDbContext = builder =>
         builder.UseSqlServer(connectionString,
          s => s.MigrationsAssembly(migrationsAssembly));

   });

我正在尝试从我的 api 生成一个令牌以将身份服务器用作客户端。有时 ConfigurationDbContext 已经被释放,有时它会在第一行抛出,有时它会在最后一行抛出

private async Task<string> CreatePaymentsTokenAsync()
{
    // Get client for JWT
    var idpClient = await this._configurationDbContext.Clients.Include(x => x.AllowedScopes)
        .FirstOrDefaultAsync(c => c.ClientId == Config.APIServerClientId);
    // Get scopes to set in JWT
    var scopes = idpClient.AllowedScopes.Select(s => s.Scope).ToArray();
    // Use in-built Identity Server tools to issue JWT
    var token = await _identityServerTools.IssueClientJwtAsync(idpClient.ClientId, 
        idpClient.AccessTokenLifetime, scopes, new[] { "MyApi" });
    return token;
}

这段代码偶尔会起作用,但大多数时候它会抛出上下文被释放的错误,有什么想法吗?

【问题讨论】:

    标签: c# asp.net-web-api .net-core identityserver4


    【解决方案1】:

    我建议不要使用底层的 DbContext,而是使用 IClientStore。

    至于这个问题 - 拥有_configurationDbContext 的类如何在 IoC 容器中限定范围?感觉它的生命周期可能比 DbContext 更长,因此最终会尝试访问已处置的实例。

    这也可能是因为您忘记在某个地方等待,导致您的代码触发并忘记了

    await CreatePaymentsTokenAsync()
    

    【讨论】:

    • 这是直接在 MVC 控制器中,范围应该是瞬态的
    • 啊哈,是的,async 方法中的可等待方法缺少 await 可能是编译器应该停止的事情。
    【解决方案2】:

    在哪里等待 CreatePaymentsTokenAsync(),该方法是否声明为异步?

    【讨论】:

    • 是的,它是异步的
    • 包含 CreatePaymentsTokenAsync 方法的类是如何在你的 DI 容器中注册的?
    • 该方法在控制器内部
    猜你喜欢
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 2016-02-22
    • 2019-10-26
    • 2011-02-26
    • 2012-10-02
    相关资源
    最近更新 更多