How to use session in asp.net core mvc Archives - Tech Insights Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Fri, 31 Mar 2023 10:43:26 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 How to use session in asp.net core mvc Archives - Tech Insights 32 32 230003556 How to Use Session State in ASP.Net Core https://reactconf.org/how-to-use-session-state-in-asp-net-core/ https://reactconf.org/how-to-use-session-state-in-asp-net-core/#respond Fri, 31 Mar 2023 10:43:26 +0000 https://labpys.com/?p=1037 In this Tutorial, we will learn How to Use Session State in ASP.Net Core. Session state in ASP.Net Core enables you to store user data and persist the data across …

The post How to Use Session State in ASP.Net Core appeared first on Tech Insights.

]]>
In this Tutorial, we will learn How to Use Session State in ASP.Net Core. Session state in ASP.Net Core enables you to store user data and persist the data across requests from the same client.

Install Required Software

  • Download NET Core SDK from here
  • Download Visual Studio or Visual Studio Code from here

Create ASP.NET Core Web Application Project

  • Open Visual Studio and Create a new project.
  • Select ASP.NET Core Web Application and give it a name.
  • Choose the template and select Create

Install NuGet Packages

Install-Package Microsoft.AspNetCore.Session

Session in ASP.NET Core

How to Enable Session in ASP.Net Core

We need to add the session middleware component to the ASP.Net Core pipeline. To enable a session in ASP.Net Core you must add any of the IDistributedCache memory caches you want to use as backing storage for the session

Also, check the previous article How to execute stored procedure in ASP.NET Core Web API | Entity Framework core

builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.IdleTimeout= TimeSpan.FromSeconds(5);
    options.Cookie.HttpOnly= true;
    options.Cookie.IsEssential= true;
});

builder.Services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2);

Configure the HTTP Request Pipeline

We need to add app.Usesession() in program.cs class.

app.UseSession();

Complete Program.cs Class

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.IdleTimeout= TimeSpan.FromSeconds(5);
    options.Cookie.HttpOnly= true;
    options.Cookie.IsEssential= true;
});

builder.Services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Create Controller

using Microsoft.AspNetCore.Mvc;
using Session_AspNet_Tutorial.Models;
using System.Diagnostics;

namespace Session_AspNet_Tutorial.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            HttpContext.Session.SetString("Message", "Hello World");
            HttpContext.Session.SetInt32("EmployeeCode", 101);
            return View();
        }

        public IActionResult Privacy()
        {
            ViewBag.Message = HttpContext.Session.GetString("Message");
            ViewBag.Employee = HttpContext.Session.GetInt32("EmployeeCode");
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

The post How to Use Session State in ASP.Net Core appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-use-session-state-in-asp-net-core/feed/ 0 1037