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

3

19

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?

Schleicher answered 29/4, 2017 at 18:1 Comment(1)
This should be a bug on MS Learn doc. I created an issue here: github.com/dotnet/AspNetCore.Docs/issues/29273Yeaton
F
40

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();
Frothy answered 29/4, 2017 at 18:12 Comment(3)
@Schleicher Just to add what @Shyju has suggested, IHttpContextAccessor would work but it may add some significant performance overhead (as reported here) and hence starting from ASP.NET Core 1.0 RC2 it is not registered by default and hence you would need to do some configuration in Starup.cs as suggested by @Shyju. An alternate solution would be to add @using Microsoft.AspNetCore.Http on top and then @HttpContext.Session.GetString("some"); would work.Pleo
çox sağol (Thanks) @shyjuPm
GetInt32 doesn't seem to be available? Need to add @using Microsoft.AspNetCore.HttpWigan
A
10

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.

Agate answered 4/8, 2018 at 12:35 Comment(0)
D
3

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")

Distend answered 9/11, 2022 at 10:55 Comment(2)
This answer should mark as right one for ASP․NET Core 3.1+. See also learn.microsoft.com/en-us/aspnet/core/fundamentals/…Yeaton
@Context.Session.GetInt32("userId")Paraguay

© 2022 - 2024 — McMap. All rights reserved.