【问题标题】:Cannot access Session object inside a helper class within my Asp.Net Core project无法访问我的 Asp.Net Core 项目中的帮助程序类中的 Session 对象
【发布时间】:2018-08-20 22:20:08
【问题描述】:

我正在尝试访问我的 ASP.NET Core 2.1 项目中的帮助程序类中的 HttpContext.Session 对象。

当我尝试访问 HttpContext.Session 时,出现以下错误。

CS0120 非静态字段、方法或属性“HttpContext.Session”需要对象引用

使用 .NET 4.x ASP.NET,可以使用“HttpContext.Current.Session”轻松访问。

这是我的课:

 public class MySession
 {

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

    }
 }

这是我的 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");
                }
            });
        }
    }

我需要在 MySession 类中注入一些东西吗?

【问题讨论】:

标签: c# asp.net-core-2.0


【解决方案1】:

您仍然可以通过HttpContext 访问Session。您必须通过IHttpContextAccessor 访问会话,顾名思义,这将允许访问控制器外部的HttpContext,以及将其作为本地成员的其他框架类。

首先您需要将访问器添加到 DI 容器中。

services.AddHttpContextAccessor();

API Reference

您需要从那里将其注入所需的类并访问所需的成员

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 中使用它
【解决方案2】:

我们还需要初始化会话对象

    private ISession _session => _httpContextAccessor.HttpContext.Session;

完整的解决方案如下。以防万一有人(像我一样)无法使用上面的代码。

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

代码取自Using Sessions and HttpContext in ASP.NET Core and MVC Core

【讨论】:

    猜你喜欢
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    相关资源
    最近更新 更多