HorseKing
HorseKing

Reputation: 454

How to store temporary data for ASP.NET Web API?

I understand that the web api should be stateless and Session is not recommended for storing temporary data, such as userId, studentId.

In some case, I do need a place to store those temporary data and I wonder which method I should use beside cookie? Because it is possible that customer disable their cookie, isn't it?

Upvotes: 1

Views: 4270

Answers (4)

nomerci
nomerci

Reputation: 1

You can use a caching. IMemoryCache are fine in simple cases:

services.AddMemoryCache();

For more complex cases use IDistributedCache(Redis, in instance):

services.AddDistributedMemoryCache();

Upvotes: 0

Shafiqul Islam
Shafiqul Islam

Reputation: 124

ASP.NET HttpContext.Current.Items allows us to hold information for an single request. We can use it to store short term information. Storing such kind information extremely helpful to send information across different custom modules or to requested pages. You have to make sure that, the data you are using in HttpContext.Current.Items is only valid for that current request and data should be flashed out automatically when request sent to browser for any new request you have to store the data again. Where as session variable is valid for every request unless session timeout not reached or we are explicitly clear the session.

For more: https://abhijitjana.net/2011/01/14/when-we-can-use-httpcontext-current-items-to-stores-data-in-asp-net/

Upvotes: 0

Fals
Fals

Reputation: 6839

You should carry the values that you need to store into the Request/Response, retieving and using them as you need. If this values are keys or something else important just Encrypt them.

Session is bad, TempData is useful in some cases when you need to store information to use in the same Request Context.

In some cases, the most of them, you can use QueryString, if the need is only for GET Request.

This way you can keep the API stateless, as Its must be.

Upvotes: 2

Thiago Custodio
Thiago Custodio

Reputation: 18387

I don't know what kind of information you want to store, but what about cache objects in your server side. You could use memcached and use the sessionId as a Key for a Dictionary.

Upvotes: 0

Related Questions