Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a session value in layout file in ASP.NET 5 MVC6

In ASP.NET 5 MVC 6 Beta 8 I need to read a session variable in in my _Layout.cshtml or alternatively get a reference to the current HttpContext.

Take note: In ASP.NET 5 referencing the Session object has changed significantly from ASP.net 4 as detailed in this question

The Context object has also been renamed to HttpContext between Beta7 and Beta8.

In My current controller I currently save the session variable like this

public IActionResult Index()
{
    HttpContext.Session.SetInt32("Template", (id));
}

In my _Layout.cshtml I need to read the above session variable. I need to reference the current HttpContext somehow e.g

HttpContext.Current.Session.GetInt32("Template");

but I don't know how to the get the current HttpContext in a cshtml file.

like image 521
devfric Avatar asked Oct 19 '15 11:10

devfric


1 Answers

The naming between Context and HttpContext is somewhat confusing. You can access the HttpContext in a view using the Context property:

@{ int x = Context.Session.GetInt32("test"); }

There is also a pending issue at the MVC repo regarding this: https://github.com/aspnet/Mvc/issues/3332

like image 93
Henk Mollema Avatar answered Oct 10 '22 20:10

Henk Mollema