Reputation: 3121
I am trying to get session like this
@HttpContext.Session.GetString("some");
But I am getting
*
An object reference is required for the non-static field ......
*
Any one with ideas?
Upvotes: 20
Views: 44756
Reputation: 1293
I know there has already been answers, but for ASP.NET Core 6 things little changed.
Again you have to add Session in services, and use it in middleware pipeline.
In Program.cs add the following
builder.Services.AddSession();
app.UseSession();
But instead of injecting HttpContextAccesor and so on, you can have direct access to Context class in view like this`
Context.Session.SetInt32("sessionInt",1);
@Context.Session.GetInt32("userId")
Upvotes: 3
Reputation: 218962
You have to inject the IHttpContextAccessor
implementation to the views and use it.
@using Microsoft.AspNetCore.Http
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
Now you can access the HttpContext
property and then Session
<p>
@HttpContextAccessor.HttpContext.Session.GetInt32("MySessionKey")
</p>
Assuming you have all the necessary setup done to enable session in the startup
class.
In your ConfigureServices
method,
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
and IApplicationBuilder.UseSession
method call in the Configure
method.
app.UseSession();
Upvotes: 43
Reputation: 6294
First enable session by adding the following 2 lines of code inside the ConfigureServices method of startup class:
services.AddMemoryCache();
services.AddSession();
In the same method add the code for creating singleton object for IHttpContextAccessor to access the session in the view.
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Now inside the Configure method of startup class you will have to add .UseSession() before the .UseMvc():
app.UseSession();
The full code of Startup class is given below:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddMemoryCache();
services.AddSession();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
// Default Route
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Then go to the view and add the following 2 lines at the top:
@using Microsoft.AspNetCore.Http
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
And then you can get the value from session variable in the view like:
@HttpContextAccessor.HttpContext.Session.GetString("some")
I have only modified the answer from @Shyju by including the complete code.
Upvotes: 10