Get unique session ID/key on server side - c#

I'm almost sure what I'm looking for exists, but I didn't finding on Microsoft documentation nor here.
I just want to get an unique ID (a string or a number, I don't really mind) from a client in ASP.NET 4.5, on the server side. I want this ID linked to a session, so different for each system that would connect to my server (like multiple computers or same client with different browsers), but the same if a user open multiple tabs on the same browser on my server.
I already looked on:
System.Web.UI.Page.ClientID: It is the name of the control (so always "__Page").
System.Web.UI.Page.UniqueID: It returns the same.
Session.LCID: I'm not sure to what it refers to, but it is the same if I connect to my server with different browsers.
Session.SessionID: Change each time I refresh the page or open it in a new tab.
Request.AnonymousID: Is null.
So all my attempts gave me an ID that changes everytime or never. Is there any way to get something from session ?

What you are looking for is in fact the Session.SessionID, however it comes with a caveat.
From MSDN:
When using cookie-based session state, ASP.NET does not allocate storage for session data until the Session object is used. As a result, a new session ID is generated for each page request until the session object is accessed. If your application requires a static session ID for the entire session, you can either implement the Session_Start method in the application's Global.asax file and store data in the Session object to fix the session ID, or you can use code in another part of your application to explicitly store data in the Session object.

I suggest using REMOTE_ADDR / REMOTE_HOST values from ServerVariables collection. These would have same values even if the user is using multiple browsers and uses different sessions from the same machine. Note that REMOTE_HOST might not always have a value.
References :
https://msdn.microsoft.com/en-us/library/system.web.httprequest.servervariables(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/ms524602(v=vs.90).aspx

Related

ASP.CORE Session using a DistributedSqlServerCache

We use a DistributedSqlServerCache to store user session data but I have noticed some unexpected/strange behaviour. So I was wondering how a DistributedSqlServerCache works under the hood to help me understand the behaviour that I am seeing.
When a user arrives at the site, immediately a DB entry is inserted, as seen below in img 1.
When the user logs out or the session times out, the session data is cleared (replaced with some arbitrary default value) and the ExpiresAtTime is also reset, as seen below in img 2.
Again, another user arrives at the site, and a new DB entry is inserted, as seen below in img 3.
But this time, if the application pool is recycled or the IIS is reset, then the below (img 4) is the result in the database:
It appears that the original session has not been emptied and also a new session is started.
For completeness, here's the code we use in StartUp.cs:
services.AddDistributedSqlServerCache(o =>
{
o.ConnectionString = "conn_string...";
o.SchemaName = "dbo";
o.TableName = "PS_PWD_SESSIONS";
});
services.AddSession();
Unless I’ve got the wrong end of the stick, this doesn’t make sense to me. I would be very grateful for any insight into this behaviour.
It's best not to worry about this too much. ASP.NET Core knows what it's doing. I think the behavior you're seeing is a result of session key vs. session id. The session id is tied to the actual physical session, persisted in the database here. However, the cookie that gets sent to the user contains only a session key. This session key is always valid and never expires. The client then always sends back this cookie with the same session key, and ASP.NET Core internally decides whether to restore the previous session or create a new one, based on whether the session has expired, etc.
In other words, the underlying data in the actual database doesn't necessarily reflect existing "sessions", at least from a client perspective. To the client, their session lives forever, but in the database it could be deleted. If there's no active session in the database to correspond with the client's session key, then ASP.NET Core just creates a new one.

Can't determine if my asp.net session implementation is correct

I am very confused in my implementation of sessions in asp.net web application. My logic is once user enters user name+password, I validate credentials and then create a new session with some user info[All I am after from this point onward is that this user has access to restricted resources and a user must never be able to access those resources unless he/she is authenticated]. This I validate on each request and the rest. Here is my issue though. I have many places in the website where I have html links, and I read that if I have a link such as
<a href='resource1.aspx'>resource 1</a>
This will generate a new session id, hence in reality invalidating the existing session id, which in my case will be treated as session expired and user is sent to login page. While reading up on this issue I came across an asp.net API method[
Response.ApplyAppPathModifier(url);
] which prepends the session id to each request hence resolving the new session id generation for each link. Though it resolves session breaking issue it does add the session id next to all of the urls and now session id can be seen in the source code( view source for web page). I really don't want to use cookies and want to use session for user sessions...Can some one please help me create a system which will work the way I wish it to ? if I am doing it utterly incorrect, I would really really appreciate a details discussion and if possible some example...Thanks you much in advance..
It looks like you are trying to use cookieless sessions which add a session id to all links in order to be able to track the sessions.
The other (much more common, standard and IMO secure) approach is to use normal sessions, which auto creates a session cookie (when you use the .Session object), and uses that to determin the current session. If you don't want a cookie you'll have to stick with cookieless, and the session id in the url.

how to preserve variable value when post back occurring

i used static variable to hold photo name and sign name and i passed these name to one page to another page through query string these work fine when i am run it in local system but when i am run it from server system and access through multiple client system and when redirect from one page to another page then there is photo name and sign name are same for all client system.
and when i m create a simple variable(not static) then it lost its value at the time of post back of page.
please give me solution for these how can i solve it
You need to use Session instead of static variables. Sessions are unique for users while static variables are shared among all the objects.
ASP.NET session state enables you to store and retrieve values for a
user as the user navigates ASP.NET pages in a Web application. HTTP is
a stateless protocol. This means that a Web server treats each HTTP
request for a page as an independent request. The server retains no
knowledge of variable values that were used during previous requests.
ASP.NET session state identifies requests from the same browser during
a limited time window as a session, and provides a way to persist
variable values for the duration of that session.
As a addition not If static members are being access by multiple thread then they must be considered for thread safety. This article give explanation of static members thread safety.
In ASP.NET, static variables are shared among all users as they are served by the same AppDomain in the w3wp-Process. When debugging the application on your development machine, you are the only user so you don't observe the same behavior.
Instead of using static variables, store the value in Session memory, e.g.:
Session["MySessionKey"] = variableValueThatYouWantToPreserve;
You can retrieve the value later on by reading from Session memory, e.g.:
var preservedValue = (PreservedValueType) Session["MySessionKey"];
For details on how to use Session memory, see this link.
If you transfer the value in a Request parameter when you access a new page and only need to preserve it on page-level, you can also use ViewState to preserve the value between PostBacks to the page.

Passing session to another sub-domain

In C# how can I pass a Session from one sub domain to another sub domain?
For instance I am using IIS localhost and I tried to send value from
http:\\localhost\site1 to http:\\localhost\site2
using the below way
In site1
Session["test"] = "My value";
In site2
Response.Write(Convert.ToString(Session["test"]));
The above method worked fine to pass values from one page to another but I need values to be passed from one sub domain to another sub domain i.e. one IIS web application to another IIS web application.
You can't do that with the default session state providers. You will have to roll your own using the provider model (SessionStateStoreProvider) see: here
You could also NOT use the provider model and do something like this
EDIT
HACK: I guess you can do that. here
I'm doing something similar by exchanging the session ID (and the associated settings) through a common database.
I.e.
site 1 writes its session ID to a database table, together with all required associated settings like test in your above example.
site 1 calls an URL on site 2, passing the session ID of site 1 as a query string parameter.
site 2 picks up the session ID that is passed as the query string parameter.
site 2 uses the passed session ID as a lookup key in the database table to fetch the value of test ("My value" in your example)
To enhance security, I also write a timestamp to the table and let site 2 only read those rows where the session ID and the timestamp (with some tolerance) matches. In addition, site 2 deletes the record after reading it.
Of course this is not straight forward and possibly not 100% of what you want to achieve, it may be some idea to build upon, though.
A session is specific to the application. Can you post from site1 to site2 (via JQuery for example). The post will allow you to send data (hidden). Then assign the querystring in your post to a new session variable on site2.

Usage of Session object in ASP.NET

I've just been given a new task to bootstrap a website created by someone else. But I'm absolutely new to Web. The website is in ASP.NET,C#. The code itself is not hard to understand except for the Session object. I don't understand where, how and why it's used.Could please someone explain the usage of Session object with a possible example?
P.S. What would these two lines mean?
lblPensValue.Text = sh.pensDec((string)Session["connSTR"], 113, 23);
and
if ((string)Session["connSTR"] == null)
Session is used to store data for the user's session on the web site. (this data store is per-user-browser session, and is subject to being wiped at any time by various application events)
It is generally used to store information across multiple page views in a user's session (ie. visit) to your website.
It can be used anywhere in code that runs in the context of the user's session; meaning inside a page, or in the appropriate application lifecycle events which run in the context of a session (such as Session Start)
As for your samples;
The first one, I can't fully explain, as I do not know what the function sh.pensDec() is supposed to do.
The second one is checking to make sure there is a value stored in that session variable, before running the code that follows.
HTTP by nature is stateless. The WebServer doesn't know any details after it processes the request and sends back to the client. Thus, any subsequent requests are like fresh requests to the server.
To Enable the Server to remember & subsequently recognize what it served to the client, ASP.NET uses various mechanisms of which Session is one of them.
Session is created per user. So, in your Page, you are fetching the "connSTR" are storing it. Whenever a subsequent request comes from the same user, by querying Session with the key
Session["connSTR"]
you get back its value. Since Session is an Object, its casted as a string in your code.
(string)Session["connSTR"] // Return value from session and casting to string
You need to understand Session, check this ASP.NET Session State Overview
ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application.
ASP.NET Session State Overview
ASP.NET Session State Examples
Look at, e.g.,
ASP.NET Wiki › State Management › Session
ASP.NET Session State Overview
the documentation for the HttpContext.Session Property

Categories