Home > Mobile >  C# ASP.NET Core MVC An object reference is required
C# ASP.NET Core MVC An object reference is required

Time:12-15

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

CodePudding user response:

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

  • Related