All About Session in ASP.NET 5

When I tried to use Session in my default project, it was nowhere to be found, and I was sent down a small rabbit hole trying to find it. This post will walk through a reminder of what Session is, where to find it in ASP.NET 5, an overview of the new extension methods available, and building our own custom extension method. Let’s get started!

windowshostasp-post

About Session?

If you’re just starting to develop in ASP.NET, you may not have encountered Session before. Session is a serialized collection of objects that are related to the current user’s session. The values are usually stored on the local server memory, but there are alternate architectures where the values can be stored in a SQL database or other distributed storage solutions, especially when your servers are part of a server farm.

You can store any data you like in Session, however any data you store will only be available to the current user as long as the session is active. This means that if that user logs out, the Session data is lost; if you need to keep this data you have to find another way to store it.

How to Find Session

ASP.NET 5 has been rewritten from the ground up to be a modular, choose-what-you-need framework. What this means is that you must explicitly include any packages you want to use in your project.

This allows us developers to maintain tight control over what functionality our ASP.NET 5 projects actually need, and exclude anything that is not necessary (all of this is just YAGNI in practice).

In our case, Session is considered to be one of these “additional” packages. In order to include that package we need to add a reference to Microsoft.AspNet.Session in the project.json file:

All About Session in ASP.NET 5 1

A screenshot of my project.json file showing the Microsoft.AspNet.Session dependency on version 1.0.0-beta4

However, that isn’t enough to get Session fully integrated into our project. We also need to inject the Session service into our Dependency Injection container in the Startup file like so:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory) 
{
...
app.UseSession();
...
}

With both of these steps in place, you can now use Session in your projects just like in any other ASP.NET application. Don’t forget to check NuGet if you can’t find the functionality you need; it is probably there and you just need to download it.

Step by Step to Use Session

ASP.NET 5 has introduced some new extension methods that we can use for accessing and storing Session values. The odd thing is that these extensions are not in Microsoft.AspNet.Session; rather, they are in Microsoft.AspNet.Http, and so we will need to add that package.

All About Session in ASP.NET 5 2

A screenshot of the project.json file, highlighting the Microsoft.AspNet.Http package, version 1.0.0-beta4

Once we’ve got that package included, we can start using the extension methods:

[HttpGet]
public IActionResult Index() 
{
var userID = Context.Session.GetInt("UserID");
var userName = Context.Session.GetString("UserName");
return View();
}

[HttpGet]
public IActionResult Default() 
{
Context.Session.SetInt("UserID", 5);
Context.Session.SetString("UserName", "John Smith");
return View();
}

The new extension methods are:

  • Get: Returns a byte array for the specified Session object.
  • GetInt: Returns an integer value for the specified Session object.
  • GetString: Returns a string value for the specified Session object.
  • Set: Sets a byte array for the specified Session object.
  • SetInt: Sets an integer value for the specified Session object.
  • SetString: Sets a string value for the specified Session object.

Why do only these extensions exist, and not GetDouble, GetDateTime, etc? I’m really not sure. If I had to guess I’d say it is to ensure that the values are serializable, but don’t quote me on that. If anybody knows the real reason, I’d love to hear it!

Creating Extension Methods

I’m not completely satisfied with these extensions; they don’t have enough functionality for my tastes, and so I’m gonna build some more. Specifically, I want to build extensions that will store a DateTime in session and retrieve it.

Here’s the method signatures for these extensions:

public static DateTime? GetDateTime(this ISessionCollection collection, string key) 
{

}

public static void SetDateTime(this ISessionCollection collection, string key, DateTime value) 
{

}

The ISessionCollection interface is exactly what it sounds like: a collection of items stored in Session.

Let’s tackle the SetDateTime() method first. DateTimes are weird because they are not inherently serializable, but they can be converted to a serializable type: long. So, we must convert the given DateTime value to a long before it can be stored.

public static void SetDateTime(this ISessionCollection collection, string key, DateTime value) 
{
collection.Set(key, BitConverter.GetBytes(value.Ticks));
}

The BitConverter class allows us to convert byte arrays into other types easily.

Now we can tackle the GetDateTime() method. There are two things we need to keep in mind when building this extension. First, it is entirely possible that there will be no value in Session for the specified key; if this happens, we should return null. Second, we are storing the DateTime as a long, and therefore we need to serialize it back into a DateTime type; luckily the DateTime constructor makes this really easy. The final code for the method looks like this:

public static DateTime? GetDateTime(this ISessionCollection collection, string key) 
{
var data = collection.Get(key);
if(data == null)
{
return null;
}

long dateInt = BitConverter.ToInt64(data, 0);
return new DateTime(dateInt);
}

Now we can use these extensions in addition to the ones already defined.

Now we’ve seen Session in action, including what package to use from NuGet, what extension methods are available, and even how to build our own extension method.

Best and Cheap ASP.NET Hosting Recommendation

asphostportalASPHostPortal.com is offering powerful ASP.NET 5 hosting for all Windows shared hosting. For their cheap plan is only from $5 a month with incredible features and outstanding support. One click Script installer to install all your favorite ASP, PHP and Javascript/Ajax scripts. Daily backup also included with all shared hosting packages.

Their robust, shared hosting plan with super speed and adequate allocated resources. Very suitable for individuals, college students and businesses which need good response time without compromising quality. For their paid service, They also give you Uptime and 30 Days money back guarantee.

About Rachel Smith