Usage of Session object in ASP.NET - c#

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

Related

Get unique session ID/key on server side

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

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.

Options for storing user information while logged in

What are some options in regards to maintaining user data while they are logged into my mvc4 site? I am building off of the Internet Application template and right now I am using User.Identity.Name to get the logged in user's username that they used to login with. I'd like to be able to also store and access several other pieces of information about the user across every page on the site. Can I still use User.Identity somehow and apply other attributes to it? I started building a ProfileModel that I could pass to views, but then I don't believe I would be able to pass other models to those views, not sure.
I'm open to suggestions as far as persistent user data, and thank you for any help.
EDIT 1: When I say persistent, I mean while they are logged in, the data itself is already stored in an external database, so I won't be doing any writing of this information, simply pulling it from the database, then holding onto it for the duration of them being logged in.
You'll want to leverage Session for that. Consider the following code:
Session["Profile"] = profileObj;
or maybe you just want to store a string:
Session["SomeSetting"] = value;
What you need to store in Session is unclear, and effectively irrelevant, you can store anything. You can access the Session from any Controller.
Then later on you can get the value out like this:
var profile = Session["Profile"];
// if the profile variable is null then it doesn't exist in Session yet
In response to #AaronLS, Session lasts the duration of the IIS session that's created when the user first accesses the site. Do keep in mind that these sessions are reset if inactive for a period of time (I believe the default IIS timeout is 20 minutes) so you'd want to leverage the null return value to know that you need to redirect the user to the login page to login again.

How to Remain loggin throughout the website

I am facing a very basic problem while building a website ; The website have 10 pages , The problem is that when i login once how can i remain logged in through out the rest of the pages ??
Since this question includes tags for asp.net and sesion variables, I'm not sure what you are missing.
On login form:
if (authentaionSuceeded){
HttpContext.Current.Session["loggedin"]="yes";
}
On all other pages (except for logout)
if (HttpContext.Current.Session["loggedin"]=="yes"){
// whatever you do for logged in users.
}
That's the basic idea. Although I prefer to access the session variable through an extension method/class that provides a type safety and a list of all session variables. The example in that answer is in VB, but you can do the same thing in c#.
There are some possible solutions as below:
Cookies: Store session information in the cookies in the page header
Hidden Form Fields: Maintain the session information in some hidden fields in the page forms
In each option, you need to generate the session key(some encrypted unique key) on the server side and on subsequent request, you should be able to validate that session key. Its better to regenerate a new session key on each request and expire it after certain interval. So for active user, it will keep getting new keys, but inactive user session will simply expire.

Categories