Session Sharing Between 2 Website - c#

I am doing session sharing between two website on same server using sqlserver session mode but it is worked on virtual directory not worked on server while uploaded the site on the server.
Both website using same database and same server.Can anybody tell me that what is i missed.

You might need to add the connection settings for session state to your live machines web.config.
<configuration>
<system.web>
<sessionState mode="SQLServer"
sqlConnectionString="Integrated Security=SSPI;data
source=SampleSqlServer;" />
</system.web>
</configuration>

You need custom session state implementation that will allow to share session between 2 different sites.
Default SQL session state indexes record with {session key (i.e. from cookies) + application ID} - as result even the same session ID on the same server will get separate information for different sites. There is no supported way to configure it to ignore application ID part.

Related

unexplained Session time out in ASP.NET

I have Webform ASP.NET 4.5 application.
In the login page Session variable is set as :(simplified related code)
Session["UserName"] = txtUserName.Text; (txtUserName.Text cannot be empty)
and then
Response.Redirect("Survey.aspx");
In survey page I have
if (Session == null || Session["UserName"] == null)
{
string errorText = "Session was timed out due to inactivity, to continue, please close All of your Browser windows and log in again";
In web.config file I have:
<system.web>
<sessionState mode="InProc" timeout="1200" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<customErrors mode="Off"> </customErrors>
</system.web>
Also on IIS itself I have
timeout :02:00:00
Still users report Session time out intermittently, after 15-20 minutes.
What this cause this?
=============================
Update: After setting it up to stateserver I get:
Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same. If the server is on a remote machine, please ensure that it accepts remote requests by checking the value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection. If the server is on the local machine, and if the before mentioned registry value does not exist or is set to 0, then the state server connection string must use either 'localhost' or '127.0.0.1' as the server name.
As noted in comments, your application pool is probably configured to recycle periodically, which will cause InProc sessions to be lost.
You also asked in comments:
What do you recommend change the app pool or <sessionState mode="StateServer "> ?
In general, I would do neither! Instead, I would design the application so that it is resilient to Session data being lost.
In your example, you're storing a username in Session. Instead, I would use Forms Authentication, in which case the username will be available to you from HttpContext.Current.User.Identity.Name: no need to store it in Session.
In general, I would only store stuff in Session that can easily be regenerated, e.g. by reading from a database. To retrieve stuff from Session, check for null and regenerate if necessary, something like:
var mySessionValue = (MyType) Session["MyKey"];
if (mySessionValue == null)
{
mySessionValue = ... regenerate value, e.g. by reading from database
Session["MyKey"] = mySessionValue;
}
...
You may be losing the session state because the app pool is being recycled. There are all sorts of reasons why the app pool might get recycled including time-outs, exceptions etc.
If you change your session state from InProc to StateServer then your session information should survive the app pool being recycled.
There are some downsides to using StateServer - the primary one is that objects added to the session have to be serializable. This is not normally a big issue.
To make StateServer work you need to make sure the ASP.NET State Server is installed and the service is running.

How to maintain state between ASP.NET MVC4 Applications in Same Domain?

I am new to MVC and I have been given a task to maintain state between applications that are in same domain - cookie would be one option ,Is there any alternate option other than cookie storage ?
you can do that by setting the domain name in web.config
<httpCookies domain=".domain.com"/>
There are several
1) Running a state server
2) Using sql server to store state
a) doing this in the web.config
3) Using some sort of Database server (mssql/nosql/oracle/...) (this is my preference. Because you do not need to rely on Microsoft to correctly save state in 1 or more db)
a)saving a guid to the cookie and then saving the important state data you need to sql server

Working with session variables within global filter

I am using a global filter in order to determine if a user is allowed to access a certain page/controller. I haven't been able to get a lot of tread of this as I'm not able to do a simple session variable creation. Here is my simplified code:
public class MyActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext context)
{
context.HttpContext.Session.Add("asdfasdf", 1234);
//Check if user is authorized in db
//...
base.OnActionExecuted(context);
}
}
Error:
System.Web.HttpException: Failed to login to session state SQL server for user '<USERNAME>'.
If I comment out Session.Add the application works fine. It's strange because the error given is completely unrelated (I think). How do I get my session variable to work in this case? Better question, is this the correct way to go about user authentication?
It seems that your application is configured to use SQL Server session state persistence. And you have a problem with the connection string in your web.config.
If you want to use SQL Server session state persistence make sure that you have correctly configured your database and specified correct connection string to it:
<configuration>
<system.web>
<sessionState mode="SQLServer"
sqlConnectionString="Integrated Security=SSPI;data
source=SampleSqlServer;" />
</system.web>
</configuration>
If you don't want to use SQL Server to persist your sessions you could switch back to InProc mode:
<system.web>
<sessionState mode="InProc" />
</system.web>
</configuration>

How to maintain same session in two different sites

let suppose i have two domains
1. abc.com
2. xyz.com
now the thing i want to do that i have a index page on both sites and there is a image on both index page , but when i click next in abc.com and image changes on abc.com at the same time i made a session variable in sql server . Now leave abc.com and come to xyz.com
the index page of xyz.com automatically gets refresh by ajax function after 2 second , now when page get refresh it will make a request to server and pick the next image name from session which we stored using abc.com and by getting the we will show the latest image on xyz.com .... Note . both sites are using the same server
can i do this ? . If yes then how ?
You can share sessions between sites using SQL server as the session manager, I did it following these instructions, works well.
these steps are taken from: Share ASP.net session between domains
ASP.NET APPLICATION : CSASPNETShareSessionBetweenSubDomains Project
Overview
Summary:
Session can be set to different modes (InProc, SqlServer, and
StateServer). When using SqlServer/SateServer mode, Session will store
in a specific SQL Server/Sate Server. If two ASP.NET Web Applications
specify the same SQL Server as Session Server, all Sessions store in
the same database. All in all, if using SQL Server Session, it is
possible to share Session between different ASP.NET Applications.
Since ASP.NET stores Session Id to cookie to specify current Session,
so in order to share Session, it is necessary to share Session Id in
the cookie.
The CSASPNETShareSessionBetweenSubDomains sample demonstrates how to
configure a SessionState Server and then create a SharedSessionModule
module to achieve sharing Session between sub domain ASP.NET Web
Applications.
Two ASP.NET Web Applications need to run in the same Root Domain (can
use different ports). Steps:
Configure SQL Server to Store ASP.NET Session State.
Run "C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regsql.exe
-S localhost\sqlexpress -E -ssadd" to add Session State support to Sql Server Express 1.
If you haven't added Session State to SQL Server, when you configure
a web site to use SQL Server Mode Session State,
System.Data.SqlClient.SqlException will be thrown saying "Invalid
object name 'tempdb.dbo.ASPStateTempSessions'."
Configure ASP.NET Web Applications to Use SQL Server to Store Session and Use specific decryptionKey and validationKey.
Add this settings to web.config file to use SQL Server Session
State:
Add this settings to web.config to use specific decryptionKey and
validationKey:
If you host the applications in IIS, please run the Application Pool
under an account who can log into the database. Otherwise
System.Data.SqlClient.SqlException will be thrown saying "Cannot
open database 'ASPState' requested by the login. The login failed."
Write SharedSessionModule Module to Achieve The Logic of Sharing Session
a. Implement Init() method to set Application Id read from
web.config.
b. Implement PostRequestHandlerExecute Event to store Session Id to
cookie with
the same domain and root path.
Configure ASP.NET Web Applications to Use SharedSessionModule Module.
Add this config to web.config to use SharedSessionModule Module:
If you run the applications in your own domains except localhost,
please don't forget to change the value of RootDomain after
publishing.
Run and Test
a. Add a new Web Page. b. Add two Buttons (used to Refresh the page and Set Session) and one Label for displaying
Session value. c. On Page_PreRender() method, read Session and display it in Label. On Button Click
Event, Set Value to Session. d. Create a new Web Site with the same config as Web Site 1, but set different value
to Session e. Now open two sites in two tabs. Now if you set Session Value in site1,
you can retrieve the same value in site2. So they use the same Session.
1 Remove Session State from Sql Server. Run
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regsql.exe -S
localhost\sqlexpress -E -ssremove" to remove Session State support
from Sql Server.

Sharing sessions across applications using the ASP.NET Session State Service

I am trying to share sessions between two web applications, both hosted on the same server. One is a .net 2.0 web forms application the other is as .net 3.5 MVC2 application.
Both apps have their session set up like this:
<sessionState
mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42424"
/>
In the webform application I am posting the the session key to the MVC app:
protected void LinkButton1_Click(object sender, EventArgs e)
{
Session["myvariable"] = "dan";
string sessionKey = HttpContext.Current.Session.SessionID;
//Followed by some code that posts sessionKey to the other application
}
I then recieve it in the MVC application and try use the same session like this:
[HttpPost]
public void Recieve(string sessionKey )
{
var manager = new SessionIDManager();
bool redirected;
bool IsAdded;
manager.SaveSessionID(HttpContext.ApplicationInstance.Context, Id, out redirected, out IsAdded);
var myVar = Session["myvariable"];
}
The key is being posted but the session does not seem to get loaded in the MVC app, i.e. sessionKey is null. Can what I am trying to do be done?
I did it this way:
Basically the idea is both apps use native .net sessionState stored in sqlserver. By using the same machine key and making a small tweak to a stored procedure – both apps can share any session keys and/or forms authenication.
Both apps would do something like this in their web.config:
<sessionState mode="SQLServer" sqlConnectionString="Data Source=.\SQLEXPRESS;User Id=test;Password=test;Application Name=AppName" />
<machineKey
validationKey="SOMEKEY"
validation="SHA1" decryption="AES"
/>
Session state db would need to be set up on a database server, that both apps can see.
Docs for doing this:
http://msdn.microsoft.com/en-us/library/ms229862(VS.80).aspx
Command that would need to be run:
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin>aspnet_regsql.exe -E -ssadd --sstype p -S .\SQLEXPRESS
Stored procedure (TempGetAppID) tweak to:
#appId int OUTPUT
AS
-- start change
-- Use the application name specified in the connection for the appname if specified
-- This allows us to share session between sites just by making sure they have the
-- the same application name in the connection string.
DECLARE #connStrAppName nvarchar(50)
SET #connStrAppName = APP_NAME()
-- .NET SQLClient Data Provider is the default application name for .NET apps
IF (#connStrAppName <> '.NET SQLClient Data Provider')
SET #appName = #connStrAppName
-- end change
SET #appName = LOWER(#appName)
The problem is that session keys are scoped to the applications, so two applications having the same session key in fact have separate sessions.
You can do one of two things:
Put both applications as a virtual directory under a common IIS Application. I don't think this is a good idea, but it will work.
Roll your own session data solution for the data you want to share. Possibly using the backend database as the common storage, if you have one that is.
Based on Justin's comment, just to clarify option 2 is not refering to the SQL state managemet for out of process sessions. I mean for you to actually manually manage the shared data for the two sessions, possibly using a database.
You can use a common Machine key to generate same Session ID inside both applications for a given user. Additionally, you should also plan on storing sessions of both applications in a common store such as ASP.NET State Service or a distributed cache.
You can use NCache distributed cache which takes provides session sharing feature between different applications. You specify same Application ID tag for both apps inside session state settings which allows you to share session object provided you have same Session ID generated for both applications.

Categories

Resources