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

4
  • Does this answer your question? How to access session from a view in ASP .NET Core MVC 1.0 Commented Dec 14, 2021 at 14:17
  • @CamiloTerevinto it does not Commented Dec 14, 2021 at 14:19
  • 1
    So what is the problem. Does exception occur? Or you just have blank space instead of actual value on the page? Commented Dec 14, 2021 at 14:20
  • @Alexander I got An object reference is required Commented Dec 14, 2021 at 14:28

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.