我来自 PHP 生态系统,现在我想将我的技能升级到 Asp.Net Core 2.0。 session 存在问题,因为这些 session 将在每次构建时被销毁,这在开发期间确实很烦人。
Asp.net 身份验证系统不会在构建/重新启动时被破坏,而 session 则会被破坏。
有没有办法让 session 像 Auth 行为一样持久?
我的解决方法是;由于我使用的是 asp.net Auth,我可以存储唯一的 id 并从数据库加载 session (包含自定义对象)。然后再次保存更改...
注意:我的应用程序是多用户的,因此我需要在每次向数据库发出请求时引用 session 中的用户 ID,以选择相关数据。
最佳答案
ASP.NET session 从未与身份验证相关。它们使用自己的存储来存储单个用户 session 期间使用的临时数据。
在 ASP.NET Core 中, session 中间件始终 uses the service registered对于 IDistributedCache。默认实现是本地内存缓存:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Adds a default in-memory implementation of IDistributedCache.
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
});
}
有两个持久存储提供程序,one for Redis和一个 SQL Server 。要使用它们,只需替换对 AddDistributedMemoryCache()
的调用,例如:
services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = @"Data Source=(localdb)\v11.0;Initial Catalog=DistCache;Integrated Security=True;";
options.SchemaName = "dbo";
options.TableName = "TestCache";
});
链接的文档页面解释了如何配置提供程序。
所有三个提供商都可以在 ASP.NET\Caching 中找到存储库。您可以使用它们作为实现您自己的提供程序的起点,例如使用 MySQL,假设还没有可用的提供程序。
您还可以配置 ASP.NET Core 使用内存缓存进行常规缓存,使用 SQL Server 或 Redis 进行分布式缓存和 session 存储,例如:
services.AddMemoryCache();
services.AddDistributedRedisCache(options =>
{
options.Configuration = "localhost";
options.InstanceName = "SampleInstance";
});
关于c# - Asp.Net Core 2.0 session 破坏了每个构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49300156/