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?
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();
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With