Yes it’s the same issue as setting machine key, all the servers must use the same key. .net core uses data protection services, which need a shared storage provider. Also data protection services generates the key, it’s not settable.. See above picking a provider.
ASP.NET Core Session state in Sql
We use a DistributedSqlServerCache and load balance for session state in web farm, so when set session and get session if change 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();
When publishing to one server, everything was ok, but publishing to web farm by load balance, when I refresh page, session and SessionId also cookie changed.
Our old project was ASP.NET MVC 5, and we added machine key on web.config that get from IIS.
Is necessary add machine key on web.config for ASP.NET Core?
Developer technologies ASP.NET ASP.NET Core
2 answers
Sort by: Most helpful
-
Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
2022-03-01T17:07:04.073+00:00 -
Michael Taylor 60,161 Reputation points
2022-03-01T15:24:36.74+00:00 Refer to the steps given here for setting up session middleware. Also refer to the instructions here for using a distributed cache.
Assuming your SQL instance is properly configured then you need to call the overload for AddSession that allows you to specify the cookie information.
The session cookie is encrypted using the standard data protection provider. You can use whatever provider you want but given a distributed environment your options are going to be limited. The list of available providers is here. If you're in Azure then it has options otherwise you could use a shared key for legacy reasons or Redis cache but any provider would work that shares data.