Part 2 - Create an ASP.NET Core MVC Project

Follow the instructions below to create an ASP.NET Core MVC web-application project and add support for sessions by configuring the ASP.NET Core Session middleware, and then add some code that stores and retrieves objects using session state.

1. In Visual Studio, select File New New Project from the menu to launch the New Project dialog.

2. In the New Project dialog, select the ASP.NET Core Web Application project type. See Figure below.

Figure 4 - Visual Studio New Project Dialog

3. Select a name for the project, and then click the “Ok” button.

4. In the New ASP.NET Core Web Application dialog, select Web Application (Model-View-Controller), ensuring that ASP.NET Core 2.0 (or higher) is selected for the .NET Core version. See Figure 4 below.

Figure 5 - Web Project Options Dialog

5. After the project is created, in Solution Explorer, find and open Startup.cs. The Startup class is where middleware is added and configured.

6. In the ConfigureServices method, add the following line of code just before the call to services.AddMvc. The line you’re adding will add services required for session state using default options (session expiry of 20 minutes, etc).

	services.AddSession(); 

7. In the Configure method, add the following line as the first line of the method. The line you’re adding adds the session middleware to the request pipeline for the application.

   app.UseSession(); 

8. Now that we’ve added support for session state, let’s add some code that uses it. Find the HomeController.cs file in the Controllers folder in Solution Explorer, and open it.

9. Add the following lines to the Index method, before the return statement, which will read the number of current views for a user from session, increment it and store it in ViewData it (as well as writing the new value back to session):

   var views = (HttpContext.Session.GetInt32("ViewCount") ?? 0) + 1; HttpContext.Session.SetInt32("ViewCount", views); ViewData["Message"] = string.Format("You visited {0} times", views); 

10. Add the following using statement to the top of the file:

   using Microsoft.AspNetCore.Http; 

11. In Solution Explorer, find and open Index.cshtml (in /Views/Home/ folder), and collapse the first div tag (which has the id attribute of myCarousel).

12. Add the following line after the collapsed div, on its own line, in order to display the value we set in the controller:

<h1>@ViewData["Message"]</h1> 

13. Save your changes, and then right-click your project and choose, Debug Start new instance to launch the web application locally using IIS Express.

Figure 5 - ASP.NET Core MVC Web Application with Session State

You have now created an ASP.NET Core MVC web application that uses the Session middleware with its default (in memory) storage of session state, to track how many times you visit the home page.