【问题标题】:Using sessions in .net core 1在 .net core 1 中使用会话
【发布时间】:2018-09-18 15:08:43
【问题描述】:

我正在尝试在 .net core webapp 中启用会话。我尝试按照here 的文档进行操作。但问题是会话没有得到持续。即使先前的请求已在会话中存储了某些内容,也会随着每个新请求生成新的会话 ID。我也没有在开发工具中看到任何 cookie。

引用的 dll

"Microsoft.AspNetCore.Session": "1.1.1",
"Microsoft.Extensions.Caching.Memory": "1.1.1"

我的启动文件看起来像这样

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc(options => { options.Filters.Add(new RequireHttpsAttribute()); });

    // Add services needed for sessions
    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromMinutes(10);
    });

    // Add in-memory distributed cache
    services.AddDistributedMemoryCache();

    // initialising other services, authentication and authorization policies
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // enable session before uisng it in pipeline
    app.UseSession();

    // setting custom user middleware
    app.UseUserMiddleware();

    // set up the mvc default route
    app.UseMvc(routes => { routes.MapRoute("default", "myDefaultRoute"); });

    // adding few other middlewares

} 

然后我在我的控制器中设置和访问会话值,就像这样

public class MyController : Controller
{
    private const string Key = "someKey";

    public async Task<ResponseModel> Get()
    {
        var id = HttpContext.Session.GetInt32(Key);
        return new ResponseModel(await _myService.GetAsync(id));
    }

    public async Task Set([FromBody] RequestModel request)
    {
        var id = await _myService.GetAsync(request.id);
        HttpContext.Session.SetInt32(Key, id);
    }
}

【问题讨论】:

  • 在开发工具的响应头中有cookie吗?
  • 什么是UseUserMiddleware?删除后还有问题吗?

标签: c# session asp.net-core .net-core


【解决方案1】:

在 ASP.NET Core 中,会话状态存储在分布式缓存中,您已将其配置为内存中。这与 ASP.NET 中的 In Proc 会话存储基本相同。由于存储在内存中的所有内容都与进程相关联,因此每当进程更改时,您的会话存储就会被擦除。

现在,只要您保持应用程序运行,它应该仍然保持请求到请求,但特别是如果您在 Visual Studio 中停止/开始调试,您将终止并重新启动进程,因此会擦除会话。

总而言之,如果您需要持久化会话,则需要使用持久存储,例如 SQL Server 或 Redis。如果您愿意,两者都可以用于开发和生产。有关如何设置持久存储的详细信息,请参阅documentation

【讨论】:

  • @ChisPratt 。以下语句对我来说看起来不正确“在 ASP.NET Core 中,会话状态存储在分布式缓存中。” Asp.Net Core 支持两种类型的缓存:内存缓存和分布式缓存。我认为语句应该类似于“在 ASP.NET Core 中,会话状态可以存储在分布式缓存中。”
  • 会话总是使用分布式缓存。有一个用于内存会话的内存分布式缓存提供程序。
猜你喜欢
  • 1970-01-01
  • 2017-04-06
  • 1970-01-01
  • 2019-04-03
  • 2019-08-16
  • 2018-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多