尚未为此应用程序或请求错误配置会话

我对 asp.net 很陌生,最近我遇到了一个例外:

System.InvalidOperationException

例外的细节表明:

尚未为此应用程序或请求配置会话。

下面是发生这种情况的代码片段:

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

我不知道为什么会这样或者这个错误到底是什么意思。 有人能解释一下是什么引起的吗?

80818 次浏览
HttpContext.Session.Add("name", "value");

OR

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

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

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

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.

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)

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

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