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?

3
  • Take a look at the following examples: thecodeblogger.com/2021/06/09/… and stackoverflow.com/questions/60337245/… I don't see the static HttpContext and Session objects being used, instead an IDistributedCache or IHttpContextAccessor. Commented Sep 27, 2022 at 3: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. Commented Sep 27, 2022 at 21:22
  • My problem was that the Microsoft.Extensions.Caching.SqlServer package version was 7.xxx and doesnt work (but withput any error). I changed to 3.1.32 and... magic! it works Commented Nov 9, 2023 at 12:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.