'ASP.NET Core Session state is changed any node
We use a DistributedSqlServerCache and load balance for session state in web farm, so when set session and get session if change node or server would not read session,
Create table in SQL:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BlogsCache]
(
[Id] [nvarchar](449) NOT NULL,
[Value] [varbinary](max) NOT NULL,
[ExpiresAtTime] [datetimeoffset](7) NOT NULL,
[SlidingExpirationInSeconds] [bigint] NULL,
[AbsoluteExpiration] [datetimeoffset](7) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
My startup
services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = Configuration.GetConnectionString("DbConnection");
options.SchemaName = Configuration.GetConnectionString("SchemaName");
options.TableName = Configuration.GetConnectionString("TableName");
});
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.IsEssential = true;
});
And also add session in the Configure method
app.UseSession();
Set and get session
var sessionValue = context.Session.GetString("MySessionKey");
if (sessionValue is null)
context.Session.SetString("MySessionKey", DateTime.Now.ToString());
await context.Response.WriteAsync($"Session id is {context.Session.Id}\n");
await context.Response.WriteAsync($"Session set is {SessionValue}\n");
When publishing to one server, everything was ok, but publishing to web farm by load balance, when I refresh page, MySessionKey and Session.Id also cookie are changed.
Session insert to database but when load balancer change node can not read session.
Our old project was ASP.NET MVC 5, and we added machine key that get from IIS on web.config.
Is adding a machine key in web.config necessary for ASP.NET Core?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
