I am very new to asp.net I recently I came across this exception:
System.InvalidOperationException
The details of the exception says:
Session has not been configured for this application or request.
Here is the code snippet where it happens:
[HttpPost] public object Post([FromBody]loginCredentials value) { if (value.username.Equals("Admin") && value.password.Equals("admin")) { HttpContext.Session.Set("userLogin", System.Text.UTF8Encoding.UTF8.GetBytes(value.username)); //This the line that throws the exception. return new { account = new { email = value.username } }; } throw new UnauthorizedAccessException("invalid credentials"); }
I have no idea why it's happening or what does this error actually mean. Can someone please explain what might be causing this?
Session can be enabled using the Configure method. Inside this method, you will have to call the UseSession method of the app object. Note: It is mandatory to call the UseSession method before the UseMvc method. //Enable Session.
To determine the runtime environment, ASP.NET Core reads from the following environment variables: DOTNET_ENVIRONMENT. ASPNETCORE_ENVIRONMENT when ConfigureWebHostDefaults is called. The default ASP.NET Core web app templates call ConfigureWebHostDefaults .
In your Startup.cs you might need to call
app.UseSession before app.UseMvc
app.UseSession(); app.UseMvc();
For this to work, you will also need to make sure the Microsoft.AspNetCore.Session nuget package is installed.
Update
You dont not need to use app.UseMvc(); in .NET Core 3.0 or higher
Following code worked out for me:
Configure Services :
public void ConfigureServices(IServiceCollection services) { //In-Memory services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(1); }); // Add framework services. services.AddMvc(); }
Configure the HTTP Request Pipeline:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With