What should I do if the current ASP.NET session is null? - asp.net

In my web application, I do something like this to read the session variables:
if (HttpContext.Current.Session != null && HttpContext.Current.Session["MyVariable"] != null)
{
string myVariable= (string)HttpContext.Current.Session["MyVariable"];
}
I understand why it's important to check why HttpContext.Current.Session["MyVariable"] is null (the variable might not have been stored in the Session yet or the Session has been reset for various reasons), but why do I need to check if HttpContext.Current.Session is null?
My understanding is that the session is created automatically by ASP.NET therefore HttpContext.Current.Session should never be null. Is this assumption correct? If it can be null, does it mean I should also check it before storing something in it:
if (HttpContext.Current.Session != null)
{
HttpContext.Current.Session["MyVariable"]="Test";
}
else
{
// What should be done in this case (if session is null)?
// Is it possible to force the session to be created if it doesn't exist?
}

Yes, the Session object might be null, but only in certain circumstances, which you will only rarely run into:
If you have disabled the SessionState http module, disabling sessions altogether
If your code runs before the HttpApplication.AcquireRequestState event.
Your code runs in an IHttpHandler, that does not specify either the IRequiresSessionState or IReadOnlySessionState interface.
If you only have code in pages, you won't run into this. Most of my ASP .NET code uses Session without checking for null repeatedly. It is, however, something to think about if you are developing an IHttpModule or otherwise is down in the grittier details of ASP .NET.
Edit
In answer to the comment: Whether or not session state is available depends on whether the AcquireRequestState event has run for the request. This is where the session state module does it's work by reading the session cookie and finding the appropiate set of session variables for you.
AcquireRequestState runs before control is handed to your Page. So if you are calling other functionality, including static classes, from your page, you should be fine.
If you have some classes doing initialization logic during startup, for example on the Application_Start event or by using a static constructor, Session state might not be available. It all boils down to whether there is a current request and AcquireRequestState has been run.
Also, should the client have disabled cookies, the Session object will still be available - but on the next request, the user will return with a new empty Session. This is because the client is given a Session statebag if he does not have one already. If the client does not transport the session cookie, we have no way of identifying the client as the same, so he will be handed a new session again and again.

The following statement is not entirely accurate:
"So if you are calling other functionality, including static classes, from your page, you should be fine"
I am calling a static method that references the session through HttpContext.Current.Session and it is null. However, I am calling the method via a webservice method through ajax using jQuery.
As I found out here you can fix the problem with a simple attribute on the method, or use the web service session object:
There’s a trick though, in order to access the session state within a web method, you must enable the session state management like so:
[WebMethod(EnableSession = true)]
By specifying the EnableSession value, you will now have a managed session to play with. If you don’t specify this value, you will get a null Session object, and more than likely run into null reference exceptions whilst trying to access the session object.
Thanks to Matthew Cosier for the solution.
Just thought I'd add my two cents.
Ed

If your Session instance is null and your in an 'ashx' file, just implement the 'IRequiresSessionState' interface.
This interface doesn't have any members so you just need to add the interface name after the class declaration (C#):
public class MyAshxClass : IHttpHandler, IRequiresSessionState

In my case ASP.NET State Service was stopped. Changing the Startup type to Automatic and starting the service manually for the first time solved the issue.

ASP.NET Technical Articles
SUMMARY: In ASP.NET, every Web page
derives from the System.Web.UI.Page
class. The Page class aggregates an
instance of the HttpSession object for
session data. The Page class exposes
different events and methods for
customization. In particular, the
OnInit method is used to set the
initialize state of the Page object.
If the request does not have the
Session cookie, a new Session cookie
will be issued to the requester.
EDIT:
Session: A Concept for Beginners
SUMMARY: Session is created when user
sends a first request to the server
for any page in the web application,
the application creates the Session
and sends the Session ID back to the
user with the response and is stored
in the client machine as a small
cookie. So ideally the "machine that
has disabled the cookies, session
information will not be stored".

Related

Session Variables - Doc Request

Sessions' variables
In all web app you can get/set sessions' variables
PHP:
$foo = $_SESSION['myVar'];
.NET (MVC, in Controller):
using System.Web.Mvc;
// ...
var foo = Session["myVar"];
I am looking for some detailed informations on sessions' variables :
Their initial purpose (what problems did they aimed to address ?)
Common use cases
Storage
Where is it stored on the system ?
Hard drive, RAM, ...
Who is storing it?
Client / Server
I guess it's server-side, so what is managing it ?
Web Server (Apache, IIS, ...) / Web App
What is the lifetime of a session's variable ?
The session, right. So when do a session start, when does it end and how do the system know when it can get rid of these variables (GC mechanism) ?
Security
Known security flaws ?
PS: I would like to allow people here to build a good documentation about this concept. Feel free to edit the question if you think some questions should be added or edited.
Purpose
Session Variables were created primarily to deal with the stateless behavior of the HTTP protocol. Because each page request was handled pretty much completely separately from each other page request, developers wanted ways to tie strings of requests together. The canonical example of this is a login page that authenticates the user and then changes the behavior of pages requested after login.
To help with this problem, many languages and/or frameworks provided the concept of a Session Variable which would let the developer store data that would be associated with a specific browser and would persist across separate requests from that same browser.
So, to take logins as an example, on the first request from a new browser, the Session Variable would be blank. Then the user would fill out authentication information and assuming it was correct, on the server side the code would set the Session Variable for that browser to contain some sort of identifier to say that his browser was authenticated. Then during subsequent requests the code could check that identifier in the Session Variable to do some specific code that required logging in.
Another common use case would be for a "wizard" workflow. You might have a multi-page form that you want the user to fill in over several separate requests. As the user fills out the form, you can add the values to the session until the user gets to the end of the form at which time you could save it in some more permanent storage.
Storage and Management
There are many ways to store Session Variables. Any sort of persistent storage that is persistent across requests will work. Probably the most basic way is to just create a separate file for each session. PHP does this by taking a session ID that it has stored as a cookie in a browser and then looks for a file with a named derived from the session ID.
You can also store Session Variables in databases, shared memory, or even in the cookie itself. Ruby on Rails stores Session Variables by encrypting the data and then setting the cookie to the encrypted data. So the session gets stored in the user's browser itself.
Most typically the Session Variable is associated with a cookie that is stored in web browser in some way. This cookie is usually managed automatically by the language or framework that the web server application is written in. The language or framework detects a new session and creates a new Session Variable that it provides to the web server application via some sort of API. The web server application can then use the API to store information in the Session Variable, to delete it, create a new one, etc... Usually the framework has some default value for the lifetime of the session, but usually this is adjustable via the API. I think the most typical default lifetime is the the lifetime of the browser process via a cookie that has a lifetime associated with the user's browser process.
Security
There are a lot of security issues around Session Variables because they are typically used to manage authorization and authentication in web applications.
For example, many applications set the session lifetime just using the lifetime associated with the cookie. Many login systems want to force the user to re-login after a specified time, but you can't trust the browser to expire the cookie when you tell it to. The browser could be buggy, could be written by a malicious person, or manipulated by the user herself to adjust the lifetime of the cookie. So if the Session Variable API you are using relies on the cookie lifetime, you may need to have a secondary mechanism that forces the Session Variable to expire even if the cookie doesn't.
Some other security issues involve storage. If you store A Session ID in a cookie and then use that Session ID as your file name to store the Session Variable in, a malicious browser can change the Session ID in the cookie to another ID and then requests from that browser would start using some other browser's session file.
Another issue is stolen session information. Through XSS or packet inspection, session information can be stolen from a users browser session and then used by a malicious user to access the other user's accounts. This sort of problem is typically mitigated by using SSL to protect the session in transit.
This page explains a lot of the security issues when using PHP's implementation of Session Variables. Ruby on Rails has a similar page that outlines the security issues with Session Variables for that platform.
So, I will be taking this question on under two considerations:
1. I am answering under PHP guidelines.
2. I am assuming that a shared hosting service is used.
Storage
With the use of shared hosting, the php.ini file holds this answer. The file is created, physically, at the path you specify through the "session.save_path" line within the php.ini file.
Source: php.net Manual
Who Stores Session
The session is TECHNICALLY stored by the SERVER but at request, obviously, by the client. So, answer: SERVER.
Source: session_start
Who Manages It
If your session.save_path is set to go somewhere on a shared hosting server, then they control the GC that destroys it or ignores it until later. Actually, instances have happened for me where other clients within the shared hosting server had their session_gc.maxlifetime at a MUCH shorter amount than I did, therefore causing my session files to be destroyed in the amount of time that THEY set (other shared users). To get around this, edit your "session.save_path" to within your OWN file tree.
Lifetime
As said previously, "session.gc_maxlifetime" controls this file's "expiration". Along with this, the "session.gc_probability" and "session.gc_divisor" should be considered, and set to "1" and "100", respectively. Google search this for further explanation.
Source: session.gc_maxlifetime
Security
I'm going to let php.net handle this, but here's the link!
Source: Security
I take an ASP.NET application scenario as an example.
In ASP.NET/MVC HttpContext.Current.Session provides access to RAM that is managed by the Server (WebServer/AppServer, IIS). In the case of the Internet Information Server, the RAM used is located inside a so called Application Pool and used by one or more Apps running inside the Web-/AppServer. The structure from the programmer's point of view is a Dictionary which means for access via C# that you can use the this[] operator to write to and read from the Session object.
// write access
var CurrentArticle = 123456;
Session["CurrentArticle"] = CurrentArticle;
//...
// read access
var CurrentArticle = 0;
CurrentArticle = (int)Session[nameof(CurrentArticle)];
The Session object provided by .NET will be created in the method Session_Start and deleted in Session_End. However, you don't have to use the System's default Session Store and can implement your own, i.e. like this:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Web;
// using MyOtherStuff;
namespace MyStuff.Server.Context
{
public class HttpSessionState : HttpSessionStateBase
{
Dictionary<string, object> _sessionStorage = new System.Collections.Generic.Dictionary<string, object>();
public override object this[string name]
{
get
{
if (HttpContext.Current == null || HttpContext.Current.Session == null)
if (!_sessionStorage.ContainsKey(name))
return null;
else return _sessionStorage[name];
return HttpContext.Current.Session[name];
}
set
{
if (HttpContext.Current == null || HttpContext.Current.Session == null)
_sessionStorage[name] = value;
else HttpContext.Current.Session[name] = value;
}
}
}
public class Current
{
/// <summary>
/// Objects stored in Cache expire after some time; compare Application
/// </summary>
public static ExpiringCache Cache = new ExpiringCache();
/// <summary>
/// Objects stored in Application don't expire
/// </summary>
public static Application Application = new Application();
public static HttpSessionState Session = new HttpSessionState();
private static System.Web.HttpServerUtility server;
public static System.Web.HttpServerUtility Server
{
get
{
if (System.Web.HttpContext.Current != null)
return Context.Current.Server;
if (server != null)
return server;
server = new System.Web.HttpApplication().Server;
if (server != null)
return server;
throw new NotSupportedException("HDitem.ApplicationServices.Current was not initialized (server)");
}
set { server = value; }
}
}
//..
}
Every new Browser connecting to your server creates a new session. If you don't care about the data from recent sessions of the same user (if your app has users) than you are probably done here.
If you want to re-connect a new session to one or more previous sessions, i.e. identified by some combination of data you have available about this user (e.g. through the request, a cookie or alike) or in the easiest form the authentication of the user than you might want to store the data of the session in Session_End rather than deleting it and recover it in Session_start or any time thereafter (as soon as you have enough data about the user of this session to identify her. In this case you need any form of Session Persistence (presumably this boils down to a Hard Disk or SSD to refer to your question) which in this case can come in any form of per-user-based storage, sometimes stored in a user-profile in a database or any file format like XML- or JSON-based.
So in other words: I don't want to generalize too much here but Session Storage is ideally very fast Memory Storage, potentially saved to any external storage if Session Persistence is implemented.
The above mentioned Session Storage is located on the server side. Modern browsers have a built in localstore that can be accessed via JavaScript. This local storage can also be used to create a session memory that can be used differently from the server-side session but can of course be synchronized in form of explicit requests or attachment to requests (cookie).

Weird behavior of IReadonlySessionState

I don't know how (and this is what I want to know).
I have an HttpHandler which implements IReadonlySessionState marker interface. My idea was not to update the Session variables in the handler. But we accidentally call code which is saving data in a session and somehow the session is saving data.
Then we moved our project to Azure and decided to use Azure Cache. Because of the change of SessionStateProvider, now the session is not saving the data (and it should not because the handler is readonly).
I want to know if there is any bug in default session provider which is causing the session to be persisted even when manipulated in Readonly Http Handler.
IReadOnlySessionState tells the session state provider that this handler doesn't need to save session state.
The handler is not obligated to refuse to save anything.
The default handler doesn't have any reason to not save session state (since it's in-process), so it always saves.

Controller SessionStateBehavior is ReadOnly and I can update Session Variable

I expect that if controller has attribute SessionStateBehavior.ReadOnly then I can't change session variables inside this controller
but I can change values.
I try this code
[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
public class GLobalController : Controller
{
public ActionResult Index()
{
Session["xxx"] = DateTime.Now.ToString();
return View();
}
see Writing to a read only session in MVC 3+
That post claims the behavior is inconsistent.
I am definitely able to write to Session in Controllers using ReadOnly.
I Would treat it like this:
Required means you are requesting a exclusive lock on Session (i.e. no parallel processing of requests for the same sessionID)
ReadOnly means you are requesting a non-exclusive lock on Session (i.e. your request still has to wait for requests with an exclusive lock to finish, but you can process requests with non-exclusive locks in parallel. However it is up to you to ensure that your code doesn't write to Session. It's not necessarily enforced by the framework)
I realize this is counter to http://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionstatebehavior.aspx
Read-only session state is enabled for the request. This means that session state cannot be updated.
but it seems you in fact can update session state under some scenarios.
According to Patrick Y. Ng (Software Engineer at Microsoft) who designed and developed the Session State engine of ASP.NET:
Even though EnableSessionState is marked as ReadOnly, in InProc state the user can still modify the session. The only difference is that the session will not be locked during the request. This limitation is by-design. And I'm sorry that it’s not documented in MSDN.
There is much more useful information about session state in this post. It is really worth reading.
This is just my interpretation:
I see that you can add to Session during the action method - after all Session is just a dictionary really. However the session is not saved at the end.
It does seem like it ought to throw an exception, but perhaps since this feature came later to the framework they decided against checking every time.
Results may vary also depending upon what session state storage you are using (inproc / sql server).

Preserve Session Variables Across HttpHandlers

I have an ASP.NET application with 5 .ashx HTTPHandlers that implement IRequiresSessionState or IReadOnlySessionState.
Upon calling the first handler I create a variable and store it in the session.
When I call the next HttpHandler the variable is not available in the session object.
I am use context.Session.
I have a global.asax where I retrieve the sessionId.
Is there a way to preserve session variables across HttpHandlers or does each Handler get its own session?
HeartAttack has a good discussion of this here:
http://weblogs.asp.net/ashicmahtab/archive/2008/09/18/how-to-use-session-values-in-an-httphandler.aspx
Basically, you need to do something like:
public class MyHandler:IHttpHandler,IRequiresSessionState
HTH's.
This should maintain session state across handlers. That is, when you log in, you only have one session for all of your requests into that domain. I'd suggest verifying that you are really logged in. Cache of course will work because that is common to all sessions but much more expensive on the server because it does not easily go away.

"HttpContext.Current.Session" vs Global.asax "this.Session"

Recently, while working on some code for an ASP.NET project at work. We needed a tracking util to take basic metrics on user activity (page hit count etc) we would track them in Session, then save the data to DB via Session_End in Global.asax.
I began hacking away, the initial code worked fine, updating the DB on each page load. I wanted to remove this DB hit on each request though and just rely on Session_End to store all the data.
All of the tracking code is encapsulated in the Tracker class, including properties that essentially wrap the Session variables.
The problem is that when I executed Tracker.Log() in the Session_End method, the HttpContext.Current.Session in the Tracker code was failing with a NullReferenceException. Now, this makes sense since HttpContext always relates to the current request, and of course in Session_End, there is no request.
I know that Global.asax has a Session property which returns a HttpSessionState that actually seems to work fine (I ended up injecting it in to the tracker)..
But I am curious, how the hell can I get the same reference to the HttpSessionState object used by Global.asax from outside of Global.asax?
Thanks in advance guys, I appreciate the input. :)
To answer the original question better:
Background
Every single page request spins up a new Session object and then inflates it from your session store. To do this, it uses the cookie provided by the client or a special path construct (for cookieless sessions). With this session identifier, it consults the session store and deserializes (this is why all providers but InProc need to be Serializable) the new session object.
In the case of the InProc provider, merely hands you the reference it stored in the HttpCache keyed by the session identifier. This is why the InProc provider drops session state when the AppDomain is recycled (and also why multiple web servers cannot share InProc session state.
This newly created and inflated object is stuck in the Context.Items collection so that it's available for the duration of the request.
Any changes you make to the Session object are then persisted at the end of the request to the session store by serializing (or the case of InProc, the HttpCache entry is updated).
Since Session_End fires without a current request in-fly, the Session object is spun up ex-nilo, with no information available. If using InProc session state, the expiration of the HttpCache triggers a callback event into your Session_End event, so the session entry is available, but is still a copy of what was last stored in the HttpContext.Cache. This value is stored against the HttpApplication.Session property by an internal method (called ProcessSpecialRequest) where it is then available. Under all other cases, it internally comes from the HttpContext.Current.Session value.
Your answer
Since the Session_End always fires against a null Context, you should ALWAYS use this.Session in that event and pass the HttpSessionState object down to your tracing code. In all other contexts, it's perfectly fine to fetch from HttpContext.Current.Session and then pass into the tracing code. Do NOT, however, let the tracing code reach up for the session context.
My answer
Don't use Session_End unless you know that the session store you are using supports Session_End, which it does if it returns true from SetItemExpireCallback. The only in-the-box store which does is the InProcSessionState store. It is possible to write a session store that does but the question of who will process the Session_End is kind of ambiguous if there are multiple servers.
Global.asax implements HttpApplication - which is what you are talking to when you call this from within it.
The MSDN documentation for HttpApplication has details on how you can get hold of it in an HttpHandler for example, and then get access to the various properties on it.
HOWEVER
Your application can create multiple instances of HttpApplication to handle parallel requests, and these instances can be re-used, so just picking it up somehow isn't going to guarentee that you have the right one.
I too would also add a note of caution - if your application crashes, there's no guarentee that session_end is going to be called, and you'll have lost all the data across all sessions, clearly not a good thing.
I agree that logging on every page is probably not a great idea, but perhaps a halfway house with some asynchronous logging happening - you fire details off to a logging class, that every now and then logs the details you are after - still not 100% solid if the app crashes, but you're less likely to lose everything.
I think you already answered your own question: usually the Session property in Global.asax and HttpContext.Current.Session are the same (if there is a current request). But in the case of a session timeout, there is no active request and therefore you can't use HttpContext.Current.
If you want to access the session from the method called by Session_End, then pass it as a parameter. Create an overloaded version the Log() method, which takes a HttpSessionState as a parameter, then call Tracker.Log(this.Session) from the Session_End event handler.
BTW: you are aware that you can not rely on the session end event in any case? It will only work as long as you have the session state in-process. When using SQL server or StateServer to mange the session state, the session end event will not fire.
The Session_End event is raised only when the sessionstate mode is set to InProc in the Web.config file. If session mode is set to StateServer or SQLServer, the event is not raised.
use Session["SessionItemKey"] to get the session value.
Okay, I am in the same problem to track the session activity. Instead of using session_end event, I have implemented the IDisposable interface and destructor to my sessiontracker class. I have modified the Dispose() method to save the session activity to DB. I invoked the method obj.Dispose() when a user clicks the logout button. If user closed the browser by mistake, then GC will call the destructor while cleaning the objects (not immediately but for sure it will call this method after sometime). The destructor method internally execute the same Dispose() method to save the session activities into DB.
-Shan
Session is available in your Global.asax file, during the Session_Start event. Maybe wait until this point to do stuff?
Remember that Session_End runs when the session times out without activity. The browser doesn't originate that event (because it's inactive), so the only time you actually will get the event is when using the InProc provider. In EVERY OTHER provider, this event will never fire.
Moral? Don't use Session_End.

Resources