[英]Session not working in ASP.Net Core Web API
我正在尝试在 ASP.NET Core Web API (.NET Core 3.1) 中使用 session 功能。 作为测试,我按如下方式配置了我的项目。
安装 NuGet package Microsoft.AspNetCore.Session
。
在Startup.cs
的ConfigureServices
中添加服务方法。
services.AddDistributedMemoryCache();
services.AddSession();
Startup.cs
的Configure
中使用 session :public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSession();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
HttpContext.Session.SetString("currentUser", "value1");
但是,我不断收到此错误。
{"type":"NullReferenceException","message":"Object reference not set to an instance of an object.","stackTrace":" at Api.Routes.MainRoute.Handler(ILogger`1 logger) in MainRoute.cs :line 16\n at Api.Controllers.MainController.MainRoute(String authorization) in MainController.cs:line 264"}
我该如何解决这个问题?
中间件的顺序很重要。 在 UseRouting 之后和 MapRazorPages 和 MapDefaultControllerRoute 之前调用 UseSession。
将您的代码更改为:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseSession();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
我不确定,但这份文件帮助我设置了 session,这是我的启动文件:
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSession();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.