【问题标题】:HttpContext.Session is null in ASP.NET Core 2.2HttpContext.Session 在 ASP.NET Core 2.2 中为空
【发布时间】:2019-07-23 12:14:13
【问题描述】:

您好,我正在尝试将 .Net Framework 4.6 应用程序迁移到 asp.net core 2.2,但无法使用 HttpContext.Session。

我可以调用 SetString 方法,但在第二次请求时,GetString 总是返回 null 值。

我尝试了在 Stackoverflow 和官方文档上找到的不同答案,但没有一个对我的案例起作用

    public void ConfigureServices(IServiceCollection services)
    {
        var appConfiguration = new AppConfigurationManager(Configuration);
        var allowedOrigins = appConfiguration.AllowedOrigins.Split(',').Select(s => s.Trim()).ToArray();

        services.AddSingleton(Configuration); // Config
        services.AddCors(o => o.AddPolicy("default", builder =>
        {
            builder.WithOrigins(allowedOrigins)
                   .AllowAnyMethod()
                   .AllowAnyHeader()
                   .AllowCredentials();
        })); // CORS

        TokenVerifier.ControlToken(services, "secretToken");
        services.AddSignalR();

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => false;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddDistributedMemoryCache();
        services.AddMvc().AddSessionStateTempDataProvider();
        services.AddSession(options =>
        {
            options.Cookie.Name = "MySession";
            options.IdleTimeout = TimeSpan.FromDays(1);
        });

        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)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseCors("default");
        //app.UseHttpsRedirection();
        app.UseAuthentication();
        app.UseSignalR(routes =>
        {
            routes.MapHub<MindHub>("/myapp");
        });
        app.UseMiddleware<ExceptionMiddleware>();
        app.UseSession();
        app.UseMvc();
    }

请注意,JWT 身份验证、CORS 和 Signalr 正在工作(可能对你们中的某些人有帮助)

【问题讨论】:

    标签: .net-core session-state httpcontext asp.net-core-2.2


    【解决方案1】:

    这是我的最终工作示例代码,可能对你们中的某些人有用。

    注意比顺序很重要。

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            string[] allowedOrigins = new string[]; // put your allowed origins here
    
            services.AddSingleton(Configuration); // Config
            services.AddCors(o => o.AddPolicy("default", builder =>
            {
                builder.WithOrigins(allowedOrigins)
                       .AllowAnyMethod()
                       .AllowAnyHeader()
                       .AllowCredentials();
            }));
            TokenVerifier.ControlToken(services, "secretToken");
            services.AddSignalR();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.Configure<FormOptions>(x =>
            {
                x.ValueLengthLimit = int.MaxValue;
                x.MultipartBodyLengthLimit = long.MaxValue; // In case of multipart
            });
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // HttpContext into ASP.NET Core
    
            // Register your stuff here
        }
    
        // 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();
                app.UseDatabaseErrorPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
    
            app.UseCors("default");
            app.UseAuthentication();
            app.UseSignalR(routes =>
            {
                routes.MapHub<YourHub>("/hubName");
            });
            app.UseMiddleware<ExceptionMiddleware>();
            app.UseHttpsRedirection();
    
            app.UseMvc();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多