What is Caching in ASP.NET Core? See Example

Caching in ASP.NET Core allows developers to store frequently accessed data temporarily, reducing server load and improving app performance. ASP.NET Core supports in-memory caching, distributed caching, and response caching.

Key Features:

  • In-memory caching for single-server apps
  • Distributed caching for multi-server or cloud apps
  • Supports expiration, sliding, and absolute timeouts
  • Improves performance and scalability
  • Easy integration with controllers and services

Example – In-memory Caching:

builder.Services.AddMemoryCache();
var app = builder.Build();

app.MapGet("/time", (IMemoryCache cache) =>
{
    if(!cache.TryGetValue("CurrentTime", out string currentTime))
    {
        currentTime = DateTime.Now.ToString();
        cache.Set("CurrentTime", currentTime, TimeSpan.FromSeconds(30));
    }
    return currentTime;
});

app.Run();

Caching in ASP.NET Core boosts app responsiveness and reduces repeated computation or database calls, ensuring faster user experiences.

Citations:

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *