15.5 C
New York
Thursday, September 11, 2025
Array

How to implement caching in ASP.NET Core minimal APIs



In-memory caching in minimal APIs

ASP.NET Core provides support for two abstractions for working with caching, IMemoryCache and IDistributedCache. While the former is used to implement in-memory caching, the latter is used to implement distributed caching.

The following use of IMemoryCache shows how you can retrieve data from the cache if the requested data is available. If the data requested is not present in the in-memory cache, the application will retrieve the data from the data store (using a repository), store the data in the in-memory cache, and return it.


app.MapGet("authors/getall", (IMemoryCache cache, 
IAuthorRepository authorRepository) =>
    {
        if (!cache.TryGetValue("get-authors", 
            out List authors))
        {
            authors = authorRepository.GetAll();
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                .SetAbsoluteExpiration(TimeSpan.FromMinutes(5))
                .SetSlidingExpiration(TimeSpan.FromMinutes(1));
            cache.Set("get-authors", authors, cacheEntryOptions);
        }
        return Results.Ok(authors);
    });

As you can see in the preceding code snippet, the cached content will reside in the memory for a maximum of 30 seconds.

Distributed caching in minimal APIs

Distributed caching enhances the performance and scalability of applications by distributing the load across multiple nodes or servers. The servers can be located either in the same network or in different networks that are spread across geographical distances.

The following code demonstrates how to implement distributed caching in a minimal API endpoint in ASP.NET Core. In this example, the endpoint returns all author records from the distributed cache if the data is available in the cache. If the requested data is not available in the distributed cache, the endpoint adds the data to the cache and then returns the data. 

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay Connected

0FansLike
0FollowersFollow
0FollowersFollow
0SubscribersSubscribe
- Advertisement -spot_img

CATEGORIES & TAGS

- Advertisement -spot_img

LATEST COMMENTS

Most Popular