How to get session value asp.net core inside a view
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.