Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading