Session has not been configured for this application or request error
asp.net Mvcasp.net Web-Apiasp.net Mvc Problem Overview
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?
asp.net Mvc Solutions
Solution 1 - asp.net Mvc
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
Solution 2 - asp.net Mvc
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?}");
});
}
Solution 3 - asp.net Mvc
I was getting the exact same error in my .NET Core 3.0 Razor Pages application. Since, I'm not using app.UseMvc()
the proposed answer could not work for me.
So, for anyone landing here having the same problem in .NET Core 3.0, here's what I did inside Configure
to get it to work:
app.UseSession(); // use this before .UseEndpoints
app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
Solution 4 - asp.net Mvc
For .NET 6:
Go to your Program.cs
first (to add the code there)
I inserted this at the last part of the builder:
builder.Services.AddSession();
I added this after app.UseAuthorization();
app.UseSession();
Final Output:
Note: I don't know if this is really the "right lines" to place the code, but this is what worked for me. (I'm still a beginner in ASP.NET as well)
Solution 5 - asp.net Mvc
If you got this issue and your startup was correctly setup: This error appeared for me when I forgot to await and async method that used IHttpContextAccessor that was injected. By adding await to the call the issue was resolved.
Solution 6 - asp.net Mvc
If you use .NET 6 add these below into your Program.cs
(may not work in older versions):
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
app.UseSession();
Be sure if builder
and app
are already declared. If it is not, add these below before the ones I said before:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
Solution 7 - asp.net Mvc
for .net core 5
Below lines should be added in startup.cs
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
app.UseSession();
should be added before
app.UseAuthentication();
app.UseAuthorization();
Below codes can be used for set the value and reading the value
this.httpContext.Session.SetString(SessionKeyClientId, clientID);
clientID = this.httpContext.Session.GetString(SessionKeyClientId);
Solution 8 - asp.net Mvc
HttpContext.Session.Add("name", "value");
OR
HttpContext.Session["username"]="Value";