ASP.NET CORE练习 - 附录 - 报错解决方法
asp.net core报错Session has not been configured for this application or request
asp.net core报错Session has not been configured for this application or request

报错原因,在程序中未先设置Session,但使用了Session,例如
HttpContext.Session.SetString("domain", "hwq2.com");

解决办法:
在Program.cs中加入:
h_builder.Services.AddSession();

app.UseSession();//注意需要在 app.Run(); 的前面
代码如下:
WebApplicationBuilder? h_builder = WebApplication.CreateBuilder(args);

// Add services to the container.
h_builder.Services.AddRazorPages();
h_builder.Services.AddSession();//添加Session

WebApplication? app = h_builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://hovertree.com/course/aspnetcore/
app.UseHsts();
}

app.UseHttpsRedirection();//将 HTTP 请求重定向到 HTTPS。
app.UseStaticFiles();//使能够提供 HTML、CSS、映像和 JavaScript 等静态文件。

app.UseRouting();//向中间件管道添加路由匹配

app.UseAuthorization();//授权用户访问安全资源。

app.MapRazorPages();//为 Razor Pages 配置终结点路由。

app.UseSession();//使用Session

app.Run();//运行应用。

参考:《创建和运行一个.net 7的asp.net core应用
收藏 列表

评论: