TOC

The community is working on translating this tutorial into Polish, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

HttpContext:

Sessions

In the previous chapter, we discussed cookies and their importance in the web world, where the need for persistence between requests is vital because of the stateless nature of the HTTP protocol. In most web frameworks, even the old school frameworks like PHP and ASP Classic, the concept of sessions exists.

Sessions vs. Cookies

While cookies are commonly used to share data between requests for longer periods of time, even several years, sessions are designed to exist for the duration of the current session. A web browsing session can be difficult to define, especially with the move from desktop/latop PC's to handheld devices, where a browsing session is commonly stopped and resumed many times. In general, you should treat data stored in the session system as temporary - it might disappear at any time, e.g. because the user closes the browser window or restarts their handheld device.

By default, session data is stored for 20 minutes from the last request. So, if you access a page and something is stored as session data for you, it will be automatically removed after 20 minutes unless you have made a new request within this time period. You can change the timeout duration when setting up sessions for your site (see below), but as mentioned, you shouldn't try to use sessions to store data for long periods of time.

So, if you are looking to store data between multiple sessions, use cookies - otherwise, the session mechanism is a great choice. To understand the different use cases, think of a classic login system, where the user can check a checkbox to "Stay logged in": If this is not checked, the login state might as well be stored as a session and then disappear when the user leaves the site e.g. by closing the browser. If it is checked, a cookie should be used instead, resulting in the user still being logged in the next time they start their computer and visit your website.

However, discussing sessions vs. cookies is a little funny, because in general, sessions can't really exist without cookies. The reason is that while cookies are stored on the device of the user (as small, plain-text files), session data is stored (temporarily, in memory) on the server. However, since your web site will likely have more than one visitor, the server needs to know which visitor a piece of session data belongs to. For this, it creates a session ID, which is stored as a so-called session-cookie on the visitor device. With this ID, the visitor can access their session data across multiple requests.

ASP.NET Core MVC: Adding support for Sessions

In previous versions of the ASP and ASP.NET frameworks, Sessions would be available right out of the box. ASP.NET Core is much more modular though, allowing you to add the building-blocks you need when you need the. Sessions are one of these building-blocks, so to we'll have to add support for it. This requires two steps:

First, you need to install the Microsoft.AspNetCore.Session NuGet package in your project. It contains all the stuff you need to support sessions. You can install it from the UI, or by using the NuGet Console: From the Tools menu, select NuGet Package Manager -> Package Manager Console. In the Console Tool window which appears, simply type the following command and press Enter:

Install-Package Microsoft.AspNetCore.Session

After the package is installed, the second and final step is to add the support to your website. It's done in the Startup.cs file, first by calling the AddSession() extensions methods in the ConfigureServices() method, like this:

public void ConfigureServices(IServiceCollection services)
{    
    services.AddSession();
    services.AddMvc();        
}

Notice that you can, optionally, pass in one or several options to be used by the Session functionality. One of the things you can configure with this approach is the Timeout duration, as described previously in this article, like this:

services.AddSession(options => 
    {
options.IdleTimeout = TimeSpan.FromMinutes(30);
    });

Secondly, you have to call the UseSession() extension method from the Configure() method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
app.UseDeveloperExceptionPage();
    }    
    app.UseSession();
    app.UseMvcWithDefaultRoute();
}

Using Sessions

With Session support enabled, we can now start using them by accessing the Session property on the HttpContext. When you include the Microsoft.AspNetCore.Http namespace, you can access several Get* and Set* methods which can be used to retrieve and store data as session data.

Allow me to demonstrate this with a complete, although very simple, example. It's basically a View with a Form, where the user can enter their name. Once submitted, the name is stored as session data and then automatically passed to the View and input field. This will allow you to see the entered name even after the redirect or reloading the page. First, the View:

@model string
<h1>Sessions</h1>
<form asp-action="SaveName" method="post">
    Your name:
    <input type="text" name="name" value="@Model" />
    <input type="submit" value="Save" />
</form>

Notice how I define the Model to be a string in the top, and then use it inside the textbox. This allows me to pass this simple string into the View from the Controller:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace HelloMVCWorld.Controllers
{
    public class SessionsController : Controller
    {
public IActionResult Index()
{
    string name = HttpContext.Session.GetString("Name");
    return View(model: name);
}

public IActionResult SaveName(string name)
{
    HttpContext.Session.SetString("Name", name);
    return RedirectToAction("Index");
}
    }
}

It's all very basic: In the Index() action, I try to fetch the session data with the GetString() method, using "Name" as the key. If its not already there, a NULL will be returned - no matter what, we simply pass it to the View() method. In the SaveName() action, which the FORM posts back to, we use the SetString() method, passing in "Name" as the key and the submitted "name" as the value. Then we redirect to the Index() action, which can now read the newly saved "Name" and display it in the textbox:

Congratulations, you have now enabled and used sessions in your ASP.NET Core project! There are a couple of additional Get* and Set* methods for you to use, e.g. GetInt32()/SetInt32() for integers and Get()/Set() for byte arrays.

Summary

Sessions can be great for storing temporary data across multiple requests in a browsing session. If you need more permanent storage, e.g. across multiple sessions, you should use cookies.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!