Hi @Pratham Jain
Now I would like to access this data in another controller in API which is called or executed when user clicks on a button on client. Please advise best way to achieve the same.
You can try to use Session or Memory Cache to store the value in the API controller.
Refer to the following sample code:
To use Session:
configure session in the program.cs file:
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
...
Then to store object in the session, we need to add the following extension:
public static class SessionExtensions
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonSerializer.Serialize(value));
}
public static T? Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default : JsonSerializer.Deserialize<T>(value);
}
}
After that, in the controller, we can refer to the following code to set or get value from session:
var countrylist = new List<Country>()
{
new Country(){ CountryId=101, CountryName="AA"},
new Country(){ CountryId=102, CountryName="BB"},
new Country(){ CountryId=103, CountryName="CC"},
};
//check if session exists
if (HttpContext.Session.Get<List<Country>>("country") == default)
{
//set value
HttpContext.Session.Set<List<Country>>("country", countrylist);
}
else
{
//get value from session.
var data = HttpContext.Session.Get<List<Country>>("country");
}
To use memory cache:
add the memory cache service in the program.cs file:
builder.Services.AddMemoryCache();
Then, in the controller, use the following code to set/get value in cache:
var cacheKey = "countrylist";
//checks if cache entries exists
if (!_memoryCache.TryGetValue(cacheKey, out List<Country> countryoutlist))
{
//setting up cache options
var cacheExpiryOptions = new MemoryCacheEntryOptions
{
AbsoluteExpiration = DateTime.Now.AddMinutes(20),
Priority = CacheItemPriority.High,
SlidingExpiration = TimeSpan.FromMinutes(20)
};
//setting cache entries
_memoryCache.Set(cacheKey, countrylist, cacheExpiryOptions);
}
var outdata = countryoutlist;
The output as below: set value in the values controller, then get the value in the todo controller:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion