In this the lesson, we learn How to handle sessions in asp.net core with example step by step
Sessions: sessions are used to share the data between multiple web pages, we will check either the user is login or not

In asp.net core sessions are enables us to save/store the user data at client side .this user data will store the dictionary on the server and we will use sessionId is used as a key.the sessionId will store at client-side cookie and cookies is sent with each every request
Steps for implementing the sessions in asp.net core
- Create an ASP.NET Core MVC Project
- Add Configurations in Startup.cs
- Add Entity model class
- Add Session Helper class
- Create Controller
- Create View page
- Add Razor View Imports page
Create an ASP.NET Core MVC Project: open Visual Studio, create a new ASP.NET Core project

Select Empty Template and Click Ok button to Finish

Add Configurations in Startup.cs: Open Startup.cs file in your project and add new configurations as given below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace SampleHtml
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSession();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSession();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Demo}/{action=Index}/{id?}");
});
}
}
}
Add Entity model class: Create a new folder named as Models. In the Models folder, you will create a new entity class name as the alike product.cs see the given below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SampleHtml.Models
{
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public string Location { get; set; }
}
}
Add Session Helper class: Create a new folder name as Helpers. In this folder, create new helper name SessionHelper.cs as given below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
namespace SampleHtml.Helpers
{
public static class SessionHelper
{
public static void SetObjectAsJson(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T GetObjectFromJson<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
}
}
}
Add Controller: Create a new folder named Controllers in your project. In this folder, create a new controller named ProductController.cs as given below:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SampleHtml.Helpers;
using SampleHtml.Models;
namespace SampleHtml.controlles
{
[Route("demo")]
public class DemoController : Controller
{
[Route("")]
[Route("index")]
[Route("~/")]
public IActionResult Index()
{
HttpContext.Session.SetInt32("age", 20);
HttpContext.Session.SetString("username", "abc");
Product product = new Product
{
Id = "product_1",
Name = "Mobiles",
Price = 5000,
Location="Hyderabad"
};
SessionHelper.SetObjectAsJson(HttpContext.Session, "product", product);
List<Product> products = new List<Product>() {
new Product {
Id = "product_1",
Name = "Let TVs",
Price = 3457,
Location="India"
},
new Product {
Id = "product_2",
Name = "Shirt",
Price = 900,
Location="USA"
},
new Product {
Id = "product_3",
Name = "Food",
Price = 2890,
Location="UK"
},
new Product {
Id = "product_4",
Name = "House",
Price = 28905,
Location="Japan"
}
};
SessionHelper.SetObjectAsJson(HttpContext.Session, "products", products);
return View("Index");
}
}
}
Add View: Add a new folder named Views. In this folder, add a new folder named Product and add new views as given below:
@{
Layout = null;
}
@using Microsoft.AspNetCore.Http;
@using SampleHtml.Helpers;
@using SampleHtml.Models;
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" href="https://tutorialshelper.com/demo/Css/dynamictable.css">
</head>
<body>
<h3>Session Page information </h3>
Age: @Context.Session.GetInt32("age")
<br />
Username: @Context.Session.GetString("username")
<h3>Product Information</h3>
@{
Product product = SessionHelper.GetObjectFromJson<Product>(Context.Session, "product");
}
Id: @product.Id
<br />
Name: @product.Name
<br />
Price: @product.Price
<br />
Location:@product.Location
<h3>List Of Products</h3>
@{
List<Product> products = SessionHelper.GetObjectFromJson<List<Product>>(Context.Session, "products");
}
<h1>How to upload multiple files in asp.net core</h1>
<table class="table blueTable" cellpadding="2" cellspacing="2" border="1">
<tbody>
@foreach (var p in products)
{
<tr>
<th>Id</th>
<td> @p.Id</td>
</tr>
<tr>
<th>Name</th>
<td> @p.Name</td>
</tr>
<tr>
<th>Price</th>
<td> @p.Price</td>
</tr>
<tr>
<th>Location</th>
<td> @p.Location</td>
</tr>
}
</tbody>
</table>
</body>
</html>
Add Razor View Imports page: Select Razor View page and click Add button to Finish and Add Inside _ViewImports.cshtml file and TagHelpers library as given below:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Run Project:

- Crud operation in asp.net core using entity framework core code first - May 22, 2020
- How to handle sessions in asp.net core with example - April 30, 2020
- How to upload multiple files in asp.net core - April 29, 2020