Search code examples
c#.net-6.0session-statewebapi

.NET 6 : Keeping a value in memory and comparing it with the input value in web api


I want to keep a code in the session and compare when the user submits the code, in .NET 6 (Not Api) I used session, but I use the same configuration in Web Api, it gives an error?

I searched a lot but could not find a suitable answer!!

If the session cannot be used in Web Api, what is the best solution to save the value except the database?

Program.Cs

builder.Services.AddSession(option =>{
option.IdleTimeout = TimeSpan.FromMinutes(10);
option.Cookie.IsEssential = true;
});

and :

app.UseSession();

When the project is executed, the following error is displayed

enter image description here


Solution

  • As mentioned in the docs the framework-provided session state management uses IDistributedCache as a backing store for session, so you need to add one:

    builder.Services.AddDistributedMemoryCache();
    

    Note that default registration (i.e. one above) actually is not distributed and actually uses in-memory cache.