0

I am trying to use distributed SQL Server Cache for session state for a ASP.NET 6 application. The code example on Microsoft documentation shows how to set up session state using in memory cache: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-6.0

But our application will be deployed to multiple servers. So I am looking for an approach to use distributed SQL Server Cache for session state.

Here is the code I am using in Program.cs:

builder.Services.AddDistributedSqlServerCache(options =>{
options.ConnectionString = builder.Configuration.GetConnectionString(
    "DistCache_ConnectionString");
options.SchemaName = "dbo";
options.TableName = "TestCache";}); // we have the corresponding table "TestCache" set up

builder.Services.AddSession(options =>{
options.IdleTimeout = TimeSpan.FromMinutes(10);
options.Cookie.IsEssential = true;});
...
app.UseSession();

When trying to set a session value in a controller, id is empty and a is null. And the "TestCache" table is also empty.

HttpContext.Session.SetString("name", "test");
 var id = HttpContext.Session.Id;
 var a = HttpContext.Session.GetString("name");

Did I miss anything for configuration? I searched online and found some examples using similar code, but all of them seem to use .NET Core 2.* or .NET Core 3.* Did anything change for .NET 6?

ld dl
  • 61
  • 4
  • Take a look at the following examples: https://thecodeblogger.com/2021/06/09/use-distributed-sql-server-cache-with-net-core-web-apis/ and https://stackoverflow.com/questions/60337245/cannot-use-httpcontext-session-in-asp-net-core I don't see the static HttpContext and Session objects being used, instead an IDistributedCache or IHttpContextAccessor. – Anthony G. Sep 27 '22 at 03:35
  • Thank you Anthony. I am using IHttpContextAccessor in my real code (just simplified it to static HttpContext in the above code example). It's still not working. And Distributed cache is on application level, it will be same for different users. but In my case, I would like to use Session state, so that the value is different for different users. – ld dl Sep 27 '22 at 21:22

0 Answers0