How to get session value asp.net core inside a view

Navigator picture Navigator · Apr 29, 2017 · Viewed 12.9k times · Source

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?

Answer

Shyju picture Shyju · Apr 29, 2017

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();