0

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?

6
  • Please post your entire Configure method - because the order of invocation of app. methods is important. Commented Sep 11, 2021 at 4:56
  • Please post the entire stack-trace of the NullReferenceException - what makes you so sure it's related to Session-state? Commented Sep 11, 2021 at 4:56
  • 1
    AddDistributedMemoryCache <-- why are you using the distributed memory-cache when you haven't configured the distributed cache client? (e.g. Redis, memcached, etc). Instead, for single and smaller web-applications you probably want just AddMemoryCache(). Commented Sep 11, 2021 at 4:57
  • I've done what you said. I used AddDistributedMemoryCache because it resolved an error like Unable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'Microsoft.AspNetCore.Session.DistributedSessionStore'. Commented Sep 11, 2021 at 5:55
  • Please read out the thread in Stackoverflow regarding sessions in API. Hopefully it will be helpful. Commented Sep 11, 2021 at 6:33

2 Answers 2

2

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(); });
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

On my project IdleTimeout was increased to fix same issue. Can be usefule in case of development or slowly performed API

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.