'Session not working in ASP.Net Core Web API

I am trying to use the session capability in ASP.NET Core Web API (.NET Core 3.1). As a test, I configured my project as follows.

  1. Install NuGet package Microsoft.AspNetCore.Session.

  2. Add service methods in ConfigureServices in Startup.cs.

services.AddDistributedMemoryCache();
services.AddSession();
  1. Use session in Configure in Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseSession();
    
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
  1. Set a session variable in one of my routes in my controller.
HttpContext.Session.SetString("currentUser", "value1");

However, I keep getting this error.

{"type":"NullReferenceException","message":"Object reference not set to an instance of an object.","stackTrace":" at Api.Routes.MainRoute.Handler(ILogger`1 logger) in MainRoute.cs:line 16\n at Api.Controllers.MainController.MainRoute(String authorization) in MainController.cs:line 264"}

How can I fix this problem?



Solution 1:[1]

The order of middleware is important. Call UseSession after UseRouting and before MapRazorPages and MapDefaultControllerRoute .

Session and state management

Change your code to this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseSession();

    app.UseAuthorization();

    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}

Solution 2:[2]

I'm not sure but this document helped me to set session, and this is my startup file:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromSeconds(10);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSession();
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Farzad
Solution 2 Tiny Wang