I am trying to use the session capability in ASP.NET Core Web API (.NET Core 3.1). As a test, I configured my project as follows.
Install NuGet package
Microsoft.AspNetCore.Session.Add service methods in
ConfigureServicesinStartup.cs.
services.AddDistributedMemoryCache();
services.AddSession();
- Use session in
ConfigureinStartup.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(); });
}
- Set a session variable in one of my routes in my controller.
HttpContext.Session.SetString("currentUser", "value1");
However, I keep getting this error.
{"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"}
How can I fix this problem?
Configuremethod - because the order of invocation ofapp.methods is important.NullReferenceException- what makes you so sure it's related to Session-state?AddDistributedMemoryCache<-- why are you using the distributed memory-cache when you haven't configured the distributed cache client? (e.g. Redis, memcached, etc). Instead, for single and smaller web-applications you probably want justAddMemoryCache().AddDistributedMemoryCachebecause it resolved an error likeUnable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'Microsoft.AspNetCore.Session.DistributedSessionStore'.