'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?



Solution 1:[1]

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.

Solution 2:[2]

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/

Solution 3:[3]

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

services.AddMemoryCache();

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

services.AddDistributedMemoryCache();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Thiago Custodio
Solution 2 Shafiqul Islam
Solution 3 nomerci