Introduction
You can easily learn how to share session states in ASP.NET from different websites on different domains.
Using the Code
The first thing you need to do is to configure your Aspstate
database. Open cmd.exe as administrator and write this command (modify it if necessary) and execute it:
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\aspnet_regsql.exe
-S [Server] -E -sstype c -d [Database] -ssadd
After that, modify TempGetAppID
Stored Procedure as below:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER PROCEDURE [dbo].[TempGetAppID]
@appName tAppName,
@appId int OUTPUT
AS
SET @appName = LOWER('King Session State')
SET @appId = 1
SELECT @appId = AppId
FROM dbo.ASPStateTempApplications
WHERE AppId = 1
IF @appId IS NULL BEGIN
INSERT dbo.ASPStateTempApplications
VALUES (@appId, @appName)
END
RETURN 0
Execute it to make sure all websites have the same AppId
in which sessions will be shared.
Now modify web.config and add these lines to it:
<system.web>
<sessionState mode="SQLServer" allowCustomSqlDatabase="true"
sqlConnectionString="Data source=.;Initial Catalog=SessionDB;User ID=???;
Password=***" timeout="60" />
</system.web>
From now the ApplicationId
of your sites will be same & your session states will be shared in all websites on the current domain. (in sub domains). To share sessionState on any website you need to set the same sessionId
on them. You need to pass sessionId from source website to destination either using GET
of POST
methods. The codes below do it for you by using GET
method (using Request.QueryString
) :
using System.Web.SessionState;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserId"] == null)
{
string sessionId = Request.QueryString["sid"];
SessionIDManager manager = new SessionIDManager();
bool isRedirected;
bool isNewSession;
manager.SaveSessionID(Context, sessionId, out isRedirected, out isNewSession);
Session["Temp"] = "Some useless data.";
Response.Redirect(Request.Path, true);
}
else
{
}
}
History
- Version 1.0: Share session states in sub domains of current domain.
- Version 1.1: Share session states in different domains.