简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM