0

I am trying to access session from the .cshtml page:

@using Microsoft.AspNetCore.Http
...
<div>
     @HttpContext.Session.GetString("role");

</div>

Controller:

public class TestController: Controller
{
     public IActionResult UserLogin(DVAAccount user)
     {
         ....
       
         HttpContext.Session.SetString("role", user.UserRole);

         return View("Index");
     }
}

However I can't seem to retrieve the session in the front-end

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
alexis
  • 31
  • 6

1 Answers1

2

mvc usually doesnt use session, so you need to add some code to your startup to use it

services.AddDistributedMemoryCache();

services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromSeconds(10);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});


.....

//app.UseRouting();

//app.UseAuthorization();

app.UseSession();

if you use Net 6+ you have to use builder.Services instead of services

Serge
  • 40,935
  • 4
  • 18
  • 45