Solved – InvalidOperationException: Session has not been configured for this application or request

This post will show you how to solve the exception “InvalidOperationException: Session has not been configured for this application or request” when you run your ASP.NET Core web application.

Basically, we get this exception because we are missing to add Session configuration or having incorrect Session configuration in the Startup.cs file.

To solve this issue, let’s verify your Startup.cs file as shown below:

  • If you are using ASP.NET Core 2.x or 1.x, please ensure that you have the two following:
    • add app.UseSession() middleware into Configure() method
    • app.UseSession() must be added before app.UseMvc()
Startup.cs
using ...

namespace MyAspNetCoreApplication
{
    public class Startup
    {
        [...]

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            [...]

            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "areaRoute",
       			template: "{area:exists}/{controller=Example}/{action=Index}");
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Example}/{action=Index}/{id?}");
            });
        }
    }
}

  • If you are using ASP.NET Core 3.x or above, please ensure that you have the two following:
    • add app.UseSession() middleware into Configure() method
    • app.UseSession() must be added before app.UseEndpoints()
Startup.cs
using ...

namespace MyAspNetCoreApplication
{
    public class Startup
    {
        [...]

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

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Leave a Reply

avatar