3

I am trying to access the HttpContext.Session object in a helper class within my ASP.NET Core 2.1 project.

When I try to access HttpContext.Session I get the following error.

CS0120 An object reference is required for the non-static field, method, or property 'HttpContext.Session'

With .NET 4.x ASP.NET, it was easily accessed with "HttpContext.Current.Session".

Here is my class:

 public class MySession
 {

    public void Foo()
    {
        HttpContext.Session.SetString("Name", "The Doctor"); // will not work
        HttpContext.Session.SetInt32("Age", 773);  // will not work

    }
 }

Here is my Startup.cs:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout = System.TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            services.Configure<ServiceSettings>(Configuration.GetSection("ServiceSettings"));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseSession();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
    }

Do I need to inject something into the MySession class?

sean
  • 1,187
  • 17
  • 25
  • add httpcontext accessor so that you can get access to the session – Nkosi Aug 20 '18 at 22:58
  • Possible duplicate of [How to access the Session in ASP.NET Core via static variable?](https://stackoverflow.com/questions/37785767/how-to-access-the-session-in-asp-net-core-via-static-variable) – RonC Aug 21 '18 at 12:23

2 Answers2

8

You can still access Session via the HttpContext. You how ever have to access the session via the IHttpContextAccessor, which as the name implies, will allow access to the HttpContext external to controllers and other framework classes that have it as a local member.

First you need to add the accessor to the DI container.

services.AddHttpContextAccessor();

API Reference

from there you need to inject it into the desired class and access the desired members

public class MySession {
    IHttpContextAccessor accessor;

    public MySession(IHttpContextAccessor accessor) {
        this.accessor = accessor;
    }

    public void Foo() {
        var httpContext = accessor.HttpContext;
        httpContext.Session.SetString("Name", "The Doctor");
        httpContext.Session.SetInt32("Age", 773);
    }
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
1

We also need to initialise the session object

    private ISession _session => _httpContextAccessor.HttpContext.Session;

Complete solution is below. Just in case anyone couldn't work out (like me) with above code.

Public class SomeOtherClass {

private readonly IHttpContextAccessor _httpContextAccessor;
private ISession _session => _httpContextAccessor.HttpContext.Session;

public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

public void TestSet()
{
    _session.SetString("Test", "Ben Rules!");
}

public void TestGet()
{
    var message = _session.GetString("Test");
} }

Code taken from Using Sessions and HttpContext in ASP.NET Core and MVC Core

Crennotech
  • 521
  • 5
  • 8