Cannot access Session object inside a helper class within my Asp.Net Core project

*爱你&永不变心* 提交于 2020-01-15 05:52:08

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/51939231/cannot-access-session-object-inside-a-helper-class-within-my-asp-net-core-projec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!