Tom Crosman
Tom Crosman

Reputation: 1285

How to store/access a session variable in ASP.NET Core Web API

I understand that a Restful API should not have session variables, but I simply want to store whether the user has AdminMode enabled or not.

I do not want to store this variable in a database.

How can I store this variable in ASP.NET Core Web API?

Upvotes: 0

Views: 3985

Answers (1)

Alexander  Mokin
Alexander Mokin

Reputation: 2304

If you application doesn't have any requirements for availablity or doesn't have to be scalable, meanig all requests goes directly to a single server, then you can get away with in-memory session variables. Just dont use it as a persistent store. E.g.

enter image description here

Otherwise, if you have your application deployed across several machines, any state on one machine usually have to be present on other machines as well so you have to synchronize it. Which is usually done with some kind of database or a queue.

enter image description here

In asp.net you have a mechanism to store to store session data

HttpContext.Session.SetString("YouData", "SomeData");

You have to set it up first, you can find detailed instructions here. By default it's going to use in-memory data store which is not a distributed cache, not a thread safe cache and not recommended for production. There are a few "out of the box" implementations for redis, sql server and NCache, you can find more information about them here

In case you use JWT token, you can store this information in a token payload

Upvotes: 2

Related Questions