In this article, we will tell you how to obtain and use session state in ASP.NET 5 applications. ASP.NET 5 is being designed so that your application is only dependent on features that it actually needs. This is achieved in large part by creating a composable framework, where the developer opts in to non-essential features – a number of which are baked in to traditional versions of ASP.NET. One of the features that this applies to is Session State.
If you are new to ASP.NET, session state is a mechanism that enables you to store and retrieve user specific values temporarily. These values can be stored for the duration of the visitor’s session on your site. In most cases, they are stored in server memory, although options exist for using persistent and/or distributed storage mechanisms if, for example, you are using multiple web servers for your application (web farm etc). This article is only focused in the in-memory option. The type of data you will use session state for is anything that relates to the current user. It might be their name, or a discount level they are entitled to, or anything that you don’t want to repeatedly query a database for.
Session State in ASP.NET 5
Session management in ASP.NET 5 is available in a Nuget package called Microsoft.ASPNet.Session. To make it available to your application, add the following entry to the dependencies node of your project.json file:
1 |
"Microsoft.AspNet.Session": "1.0.0-beta5" |
The beta number has been updated to the latest version and no longer corresponds with the image You should see “Restoring…” appear next to the References node in Solution Explorer and the session package being added.
Now that the package is available to your application, you can opt in to using it. You do this in the Configure
method of the Startup
class (Startup.cs file).
1 |
app.UseInMemorySession(); |
The UseInMemorySession
method sets up session state to use server memory, which is the same as in traditional ASP.NET by default. The method takes an optional IMemoryCache
object as a parameter if you want to change the default storage location, and an Action<SessionOptions>
delegate that enables you to change the default options such as the location for session cookies, or the default timeout period (which is 20 minutes as in previous versions). If you want sessions to expire 30 minutes after the last activity, you would do so like this:
1 |
app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(30)); |
You can start setting and getting session values after you have referenced Microsoft.AspNet.Http
in your controller:
1 |
using Microsoft.AspNet.Http; |
There are three methods that enable you to set session values: SetInt32, SetString and Set, which takes a byte array as an argument. This is very different to the traditional session API, which allows you to set a session value by assigning any type to a session key. The new session framework stores items as byte arrays, and internally, SetInt32 and SetString converts the ints and strings that you pass to a byte array. The main reason behind this decision appears to be to ensure that session values are serialisable for storage on remote servers. Here’s how you would use the SetInt32 and SetString methods from within your controller to create and set some session variables:
1 2 3 4 5 6 |
public IActionResult Index() { Context.Session.SetString("Name", "Mike"); Context.Session.SetInt32("Age", 21); return View(); } |
Here’s how you might retrieve those values to be passed to a View:
1 2 3 4 5 6 |
public IActionResult About() { ViewBag.Name = Context.Session.GetString("Name"); ViewBag.Age = Context.Session.GetInt32("Age"); return View(); } |
There is also a Get method that returns a byte array. As I mentioned earlier, if you want to set other types as session variables, you need to take care of serialisation yourself. You could do this at the point of setting values, but a more reusable approach can be achieved by creating your own extension methods on ISessionCollection. The following example shows how you might implement GetBoolean and SetBoolean methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public static class SessionExtensions { public static bool? GetBoolean(this ISessionCollection session, string key) { var data = session.Get(key); if (data == null) { return null; } return BitConverter.ToBoolean(data, 0); } public static void SetBoolean(this ISessionCollection session, string key, bool value) { session.Set(key, BitConverter.GetBytes(value)); } } |
Now you can use these methods too:
1 2 3 4 5 6 7 |
public IActionResult Index() { Context.Session.SetString("Name", "Mike"); Context.Session.SetInt32("Age", 21); Context.Session.SetBoolean("Liar", true); return View(); } |
1 2 3 4 5 6 7 |
public IActionResult About() { ViewBag.Name = Context.Session.GetString("Name"); ViewBag.Age = Context.Session.GetInt32("Age"); ViewBag.Liar = Context.Session.GetBoolean("Liar"); return View(); } |
There are two other methods of interest. One is the Remove method which allows you to delete individual values from the session collection by key and the other is the Clear method. This removes all keys and values associated with the session. There is no obvious counterpart to the pre-ASP.NET 5 Abandon method which ends the session.
Session Events
In ASP.NET 5, you can query the session collection using middleware to confirm if a session has already been established to replicate the Session_Start
event, but there are no plans to introduce an equivalent to Session_End
. Since one of the driving forces behind ASP.NET 5 is “cloud-readiness”, the focus on session management design has been to make it work in a distributed scenario.Session_End
only ever fired when sessions used inproc
mode (local server memory).
Looking for ASP.NET 5 Hosting on European Server? We can help you a lot!
hostforlifeasp.net is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. Our service is ranked the highest top spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.