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.

Make Your ASP.NET Site Load So Fast

Microsoft ASP.NET has created a strong hold on the web development market. This program allows the web developer to create web applications that are dynamic in nature. This technology has been designed in a fashion to link employees, customers and business all together.

fast network

If you read the internet and all of the websites dedicated to Asp.Net you will inevitably read about the wonders of the DataGrid, DataList, and Repeater controls. While each of these has its place, if you are only displaying data there is a much faster and more efficient means to do so.

Let’s say you have a page that displays articles based on a query string. Take my article pages for instance. Each article is stored in a database and displayed on the page based on the unique id of the article as stored in the database.

A normal asp page execution procedure goes something like this. The code queries the database based on the Article I.D. and then brings back that information to the page where you display it in the fashion that you would like. This is a fairly straight forward approach with asp and is done all the time.

So how do we speed up our asp.net pages?

Use Asp.Net Caching!

This is a no-brainer, and I won’t go into the brilliance or details of asp.net caching here because at the time of this writing Google has 2,780,000 articles on the topic. Basically instead of querying the database each time the page is loaded you only query the database once and load that result into the system cache. Subsequent calls to load the page retrieve the data from the cache as opposed to the database which gives you an instant and considerable performance boost. You can then set the cache for how long the cache should store the information as well as many other features. If you are not using the cache, you should be whenever possible!

If possible, do NOT use the standard Asp.Net controls.

That’s right. The standard asp.net controls are designed for rapid development and not page performance. They allow you to design pages that grab and display data very quickly but their actual performance suffers because of the extra overhead which is there for ease and speed of development time and not page execution speed.

Instead, create either a User Control or even better yet a Web Custom Control which is by far the fastest performance wise and really quite easy to create and use.

Use an SqlDataReader or even better yet use a set based command for Sql Server data retrieval and simply execute that one command against the database.

An asp.net SqlDataReader is a fast forward only datareader that closes the connection after it reads the last set of results. Now for my article pages we are only returning 1 particular result. In this case we would opt for the set based command. If you had more than 1 result returned, in your table of contents for instance, you would use the SqlDataReader because you are returning multiple sets of results.

Set based commands are stored procedures that bring back data through parameters as opposed to a result set which then in turn needs to be looped through to obtain your data. So instead of writing your stored procedure like the following which brings back 1 result set:

Select Title, Body, Author
From Articles
Where ArtID = 215

We can write it using a set based command like this.

Create Procedure mysp_GetArticle

@Title varchar(200) Output,
@Body varchar(8000) Output,
@Author varchar(500) Output

As

Select @Title = Title, @Body = Body, @Author = Author
From Articles
Where ArtID = 215

GO

The above query will return only the three parameters called for and not a result or record set so you don’t have to then walk through the returned record set that has only 1 result in it anyway. This second little process of work decreases your performance so you should avoid it whenever possible. Combine this technique with the asp.net cache.

Use Classes and ArrayLists as opposed to returning an SqlDataReader.

Create a class and then if there are more than one set of results store those results into individual instantiations of that class. Finally store each of those classes into an ArrayList. You can then store only that ArrayList into the asp.net cache. So instead of getting the results back from a SqlDataReader when loading your page you get them from the ArrayList which is stored in the cache. Nice huh?

Finally… you want to incorporate all of these techniques into your final results which would be performed in the following manner and sequence.

On the first time the page loads, query the database and return all of your data storing it into individual classes. Then store each of those classes into an ArrayList. If you only have one single result you may store only the class into the cache. Then take your ArrayList and store it into the cache.

Next create a Web Custom Control and pass the cached ArrayList to the custom control and loop out your data using the HtmlTextWriter which is very fast. Remember each subsequent call to load the page will be called from the cache which stores your ArraList of classes or your single class.

Certainly it takes a significant amount of additional coding to do it in this fashion, especially when you take proper error handling into consideration, but if you follow this approach your pages will be screeching fast, you will immediately notice the difference, and your asp.net pages will execute in the proper sequence – Data handling in the Page_Load function and the html display in the Page_Render function.

Further, you will be glad you did and so will your visitors.

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.