I tried working with session on ASP.NET Core 6.0 MVC but could not make it work as shown in the docs - https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-6.0
I added the session middleware on program.cs.
builder.Services.AddSession();
app.UseSession();
On the controller I am storing current datetime on session:
HttpContext.Session.SetString("CurrentDateTime", DateTime.Now.ToString());
Till now everything is fine.
But problem is I am getting error when on the view I am trying to access it like this:
@HttpContext.Session.GetString("CurrentDateTime")
The error is:
Severity Code Description Project File Line Suppression State Error (active) CS0120 An object reference is required for the non-static field, method, or property 'HttpContext.Session' UnderstandingControllersViews E:\Yogesh\SEO\Yogihosting\3\UnderstandingControllersViews\UnderstandingControllersViews\Views\Example\SessionExample.cshtml 2
How to make it work can anybody help?
CodePudding user response:
You need to inject IHttpContextAccessor
implementation to your View
and use it to get the Session
object as required:
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
//Get object from session
var mySessionObject= HttpContextAccessor.HttpContext.Session.GetString("CurrentDateTime");
}
<h1>@mySessionObject</h1>