State Management in .NET Core

Pratham Jain 221 Reputation points
2023-01-25T13:53:25.6766667+00:00

Hi All,

I am developing an application in .NET Core with angular client. In my application I have scenario where I have data in List<List<Employee>> in one controller in .NET Core API.

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.

Regards,

Pratham

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,138 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,006 Reputation points Microsoft Vendor
    2023-01-26T06:43:45.8333333+00:00

    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:

    image1


    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

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,036 Reputation points
    2023-01-25T16:59:11.48+00:00

    this seems to be a design flaw. the angular app has the state information, why would the server also? anyway the solution is a server cache and key that is returned to the angular app. the key can be passed in the second request.


  2. AgaveJoe 26,186 Reputation points
    2023-01-25T19:03:49.0266667+00:00

    How can I access the server cache and use it in another request? Can you please share the working sample?

    The link I provided talks about different types of cache scenarios and has a link to in-memory cache. I think in-memory cache is what you're interested in but I'm not sure. Is the cache specific to a user? Or is the cache global to the application?

    Assuming you read in-memory cache doc, it should be clear a key is need to fetch the data from cache. Your Angular application must persist this key and send the key to the controller action to fetch the cache.