102425074
102425074

Reputation: 811

Why session is getting null in ASP.NET Core web api in .net core 3.0?

I use the session in my project yet. It works well in the localhost. After I published to the server, the session works if I post by the postman, but not works if post by the remote server.

I found the same problem in Session variable value is getting null in ASP.NET Core

I follow the way in the topic above but still no works.

Here is my code:

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

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {            
            services.AddScoped<Global>();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.Configure<GzipCompressionProviderOptions>(options => options.Level = System.IO.Compression.CompressionLevel.Optimal);
            services.AddMvc(
                options =>
            {
                options.OutputFormatters.Add(new Classes.XmlSerializerOutputFormatterNamespace());                
            }
            )
                .AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix,
                LocalizationOptions => LocalizationOptions.ResourcesPath = "Resources").AddXmlSerializerFormatters().AddXmlDataContractSerializerFormatters();
            services.AddLocalization(options => options.ResourcesPath = "Resources");


            services.AddHttpsRedirection(options =>
            {
                options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
                options.HttpsPort = 443;
            });
            services.AddHsts(options =>
            {
                options.Preload = true;
                options.IncludeSubDomains = true;
                options.MaxAge = TimeSpan.FromDays(60);
            });
            services.AddDistributedMemoryCache();

            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddSession(options =>
            {                
                options.IdleTimeout = TimeSpan.FromHours(1);                           
                options.Cookie.IsEssential = true;
            });           
        }

        [Obsolete]
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");                
                app.UseHttpsRedirection();
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            var SupportedCultures = new List<CultureInfo> 
            {
                 new CultureInfo("en"),
                 new CultureInfo("zh-Hans"),
                 new CultureInfo("zh-Hant")
            };

            var options = new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("zh-Hans"),
                SupportedCultures = SupportedCultures,
                SupportedUICultures = SupportedCultures,
            };
            app.UseRequestLocalization(options);
            var requestProvider = new RouteDataRequestCultureProvider();
            options.RequestCultureProviders.Insert(0, requestProvider);
            app.UseStaticFiles();

            app.UseStatusCodePagesWithReExecute("/StatusCode/{0}");

            app.UseRouting();
            app.UseAuthorization();
            app.UseSession();

            app.UseRouter(routes =>
            {
                routes.MapMiddlewareRoute("{culture=zh-hans}/{*mvcRoute}", subApp =>
                {
                    subApp.UseRequestLocalization(options);
                    subApp.UseRouting();
                    subApp.UseEndpoints(mvcRoutes =>
                    {
                        mvcRoutes.MapControllerRoute("default", "{culture=zh-hans}/{controller=Home}/{action=Index}");
                        mvcRoutes.MapControllerRoute("home.html", "{culture=zh-hans}/{controller=Home}/{action}.html");
                    });
                });
            });
        }
    }

And here is the controller:

[HttpPost]
public async Task<IActionResult> abc(string i)
{
     if (HttpContext.Session.GetInt32(i) == null)
     {                
         HttpContext.Session.SetInt32(i, 1);
         _logger.LogInformation("Session is :" + HttpContext.Session.GetInt32(i).ToString());
         return Ok("First time.");
     }
     else
     {
        return Ok("Ran yet.");
     }

     return Ok(null);
}

As you see, I have made a test on the controller by a logger. The session works well after setting & before return( not only in localhost but also in server).

However, when the remote server posts a request to the server, the session always gets null.

What's wrong with this?

Upvotes: 1

Views: 2772

Answers (1)

102425074
102425074

Reputation: 811

I have read about the Microsoft official tutorial:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.0

It is said:

ASP.NET Core maintains session state by providing a cookie to the client that contains a session ID, which is sent to the app with each request. The app uses the session ID to fetch the session data.

That means it needs cookies to get the session. In short, my project just needs to get/set a static variable with an expiration so I consider I should use a session for best. And now I don't think I need to use cookies in my project yet.

At the end of the article, I notice another thing: In-memory caching https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-3.0

Then I make a test to use In-memory caching to replace the session. Well, it works well.

Upvotes: 1

Related Questions