Keselme
Keselme

Reputation: 4249

Session has not been configured for this application or request error

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?

Upvotes: 104

Views: 123278

Answers (9)

yannis_t
yannis_t

Reputation: 29

For Razor Pages ASP.NET Core application in .NET5 (needs testing on newer runtime) :

In startup.cs inside ConfigureServices I added services.AddSession() in order to register the session service

public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
**services.AddSession();** 
}

In Configure method I also added app.UseSession() in order to enable the session for the application

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{app.UseDeveloperExceptionPage();}
else
{app.UseExceptionHandler("/Error");}
app.UseStaticFiles();
**app.UseSession();** 
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>{endpoints.MapRazorPages();});
}

Upvotes: 3

Mahesh ML
Mahesh ML

Reputation: 570

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

Upvotes: 6

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

Upvotes: 5

paraJdox1
paraJdox1

Reputation: 973

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:

enter image description here


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)

Upvotes: 35

amd3
amd3

Reputation: 846

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.

Upvotes: 1

Austin Born
Austin Born

Reputation: 1691

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

Upvotes: 156

Techiemanu
Techiemanu

Reputation: 646

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?}");
     });
 }

Upvotes: 37

Giorgos Betsos
Giorgos Betsos

Reputation: 72165

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

Upvotes: 21

Debashish Saha
Debashish Saha

Reputation: 336

HttpContext.Session.Add("name", "value");

OR

HttpContext.Session["username"]="Value";

Upvotes: -6

Related Questions