ASP.NET 核心 "An error occurred while starting the application" 在配置中添加 UseSession() 之后

ASP.NET Core "An error occurred while starting the application" after adding UseSession() in config

正如标题所说,在将 UseSession() 添加到我的配置后,我得到:“启动应用程序时发生错误。.NET Core 4.6.28801.04 X64 v4.0.0.0 | Microsoft.AspNetCore.Hosting 版本 2.2.7-servicing-10089 | Microsoft Windows 10.0.18363 |" 当 运行 应用程序时。这是我看到的唯一消息。

如果我想让应用程序再次开始工作,我只需注释掉 UseSession() 调用。所以这是我得到的最好的提示。现在我确实觉得很奇怪,我不必导入(打开)库 Microsoft.AspNetCore.Session,但是如果我从包中删除它,那么 UseSession() 找不到扩展方法。

open Microsoft.AspNetCore.Session //not needed according to the compiler?
let configureApp (app : IApplicationBuilder) =
      app
        .UseCors(configureCors)
        .UseStaticFiles()
        .UseAuthentication()
        .UseSession() // <------- crashes the startup
        .UseGiraffe(webApp)

我将那些链式调用分成单独的调用,看看应用程序是否会在 UseSession() 行抛出异常,但事实并非如此。它在主 WebHostBuilder.Build().运行() 方法中崩溃。

我已阅读 docs on how to add the session, I've payed attention to the order of the middleware,我已清理项目,更新所有依赖项,重新启动 visual studio(2019 Pro,如果重要的话),重新启动计算机,删除并重新安装 Microsoft.AspNetCore.Session nuget包.

我的目标是 .NET core 2.1(尽管我正在使用 3.1 SDK 进行编译)。该应用程序是用 F# 编写的,我使用 Giraffe 作为我的 Web 框架(位于 ASP.NET 核心之上)。

关于如何解决这个问题有什么想法吗?或者我应该采取的方向来更好地诊断? 我唯一的直觉是 nuget 包不能很好地协同工作。

这些是对 web 项目的依赖:

FSharp.Data
Microsoft.AspNetCore.Cors
Microsoft.AspNetCore.Hosting
Microsoft.AspNetCore.Diagnostics
Microsoft.AspNetCore.Server.Kestrel
Microsoft.AspNetCore.Server.IISIntegration
Microsoft.AspNetCore.StaticFiles
Microsoft.AspNetCore.Authentication.Cookies
Microsoft.AspNetCore.Authentication.JwtBearer
Microsoft.AspNetCore.Session
Microsoft.Extensions.Logging.Console
Microsoft.Extensions.Logging.Debug
Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Configuration.Json
Microsoft.FSharpLu.Json
Giraffe
Giraffe.SerilogExtensions
Serilog.Sinks.RollingFile

非常感谢您抽出宝贵的时间。

终于想通了。我跳过了注册分布式缓存的步骤:

To enable the session middleware, Startup must contain: Any of the IDistributedCache memory caches. The IDistributedCache implementation is used as a backing store for session. For more information, see Distributed caching in ASP.NET Core.

在文档的 common errors section 中指出:

"Unable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'Microsoft.AspNetCore.Session.DistributedSessionStore'." This is usually caused by failing to configure at least one IDistributedCache implementation.

我发现 enable the standard log wp78de 的建议非常有用。错误消息最终出现在日志中,从那里很容易修复:

let configureServices (services : IServiceCollection) =
services.AddGiraffe() |> ignore

//THIS LINE WAS MISSING
services.AddDistributedMemoryCache() |> ignore

services.AddSession(fun options ->
  options.IdleTimeout <- TimeSpan.FromMinutes(30.0)
  options.Cookie.HttpOnly <- true
  options.Cookie.IsEssential <- true)
|>ignore