【发布时间】:2021-11-07 09:53:41
【问题描述】:
我正在尝试使用 ASP.NET Core Web API (.NET Core 3.1) 中的会话功能。作为测试,我将我的项目配置如下。
-
安装 NuGet 包
Microsoft.AspNetCore.Session。 -
在
ConfigureServices中添加服务方法Startup.cs。
services.AddDistributedMemoryCache();
services.AddSession();
- 在
Configure中使用会话Startup.cs:
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":"未设置对象引用 到一个对象的实例。","stackTrace":" at MainRoute.cs:line 中的 Api.Routes.MainRoute.Handler(ILogger`1 logger) 16\n 在 Api.Controllers.MainController.MainRoute(字符串 授权)在 MainController.cs:line 264"}
我该如何解决这个问题?
【问题讨论】:
-
请发布您的整个
Configure方法——因为app.方法的调用顺序很重要。 -
请发布
NullReferenceException的整个堆栈跟踪 - 是什么让您如此确定它与会话状态相关? -
AddDistributedMemoryCache分布式内存缓存? (例如 Redis、memcached 等)。相反,对于单个和较小的 Web 应用程序,您可能只需要AddMemoryCache()。 -
我已经按照你说的做了。我使用了
AddDistributedMemoryCache,因为它解决了像Unable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'Microsoft.AspNetCore.Session.DistributedSessionStore'.这样的错误 -
请阅读Stackoverflow 中有关 API 会话的线程。希望对您有所帮助。
标签: c# asp.net-core-webapi .net-core-3.1