Boosting Workflow Efficiency with Power Automate & Caching

Caching is a crucial technique for improving the performance of ASP.NET Core Web APIs. In this example, I'll walk you through implementing response caching, distributed caching using Redis, and in-memory caching in an ASP.NET Core Web API.

Step 1. Create a new ASP.NET Core Web API project using Visual Studio or the .NET CLI

Create a new Web API project using visual studio or using a command line interface.

Step 2. Install the required NuGet packages for caching

Using NuGet Package Manager Console:

Install-Package Microsoft.Extensions.Caching.Memory
Install-Package Microsoft.Extensions.Caching.StackExchangeRedis

Using .NET CLI

dotnet add package Microsoft.Extensions.Caching.Memory
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

Step 3. Configure caching services in the Startup.cs file

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

Author: Sardar Mudassar Ali Khan
public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        // Add memory caching
        services.AddMemoryCache();

        // Add distributed caching using Redis
        services.AddStackExchangeRedisCache(options =>
        {
            options.Configuration = "localhost:6379"; // Here You Can Use Your Own Radis Cache 
            Server
            configuration
            options.InstanceName = "SampleApp:";
        });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Step 4. Implement caching in your controllers

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using System;

Author: Sardar Mudassar Ali Khan
[ApiController]
[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
    private readonly IMemoryCache _memoryCache;
    private readonly IDistributedCache _distributedCache;

    public ValuesController(IMemoryCache memoryCache, IDistributedCache distributedCache)
    {
        _memoryCache = memoryCache;
        _distributedCache = distributedCache;
    }

    [HttpGet("memory")]
    [ResponseCache(Duration = 60)] // Response caching for 60 seconds
    public IActionResult GetValueFromMemoryCache()
    {
        // Check if value exists in memory cache
        if (_memoryCache.TryGetValue("cachedValue", out string value))
        {
            return Ok(value);
        }

        // Cache the value in memory
        value = "Value from memory cache";
        _memoryCache.Set("cachedValue", value, TimeSpan.FromSeconds(30));

        return Ok(value);
    }

    [HttpGet("distributed")]
    public IActionResult GetValueFromDistributedCache()
    {
        // Check if value exists in distributed cache
        byte[] cachedBytes = _distributedCache.Get("cachedBytes");
        if (cachedBytes != null)
        {
            string value = System.Text.Encoding.UTF8.GetString(cachedBytes);
            return Ok(value);
        }

        // Cache the value in distributed cache
        string newValue = "Value from distributed cache";
        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(newValue);
        DistributedCacheEntryOptions options = new DistributedCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60) // Cache for 60 seconds
        };
        _distributedCache.Set("cachedBytes", bytes, options);

        return Ok(newValue);
    }
}

In this example, we've implemented caching techniques in an ASP.NET Core Web API:

The GetValueFromMemoryCache action uses in-memory caching. It first checks if the value is available in the memory cache. If not, it sets the value in the memory cache with a specified expiration time.

The GetValueFromDistributedCache action uses distributed caching with Redis. It checks if the value exists in the distributed cache. If not, it sets the value in the distributed cache with an expiration time.

Make sure to replace the Redis server configuration in the Startup.cs with your actual Redis server information.

Step 5. Run the application

Run the application and test the caching endpoints using a tool like Postman or a web browser. Observe the response headers indicating cache control and check the cache behavior using appropriate tools.

By utilizing caching techniques like response caching, in-memory caching, and distributed caching, you can significantly enhance the performance of your ASP.NET Core Web API. Caching helps reduce the load on your server, improve response times, and optimize the overall user experience.

Caching is a powerful technique in ASP.NET Core Web APIs to enhance performance by storing frequently used data in memory or distributed storage, reducing the need to recompute or fetch the same data repeatedly. In this example, we covered response caching, in-memory caching, and distributed caching using Redis, each serving specific scenarios to optimize data retrieval and response times.

Here's a recap of the key takeaways:

  1. Response Caching: By using the [ResponseCache] attribute, you can easily cache the entire response of an action method, reducing the load on your server and improving client-side response times. This is effective for data that doesn't change frequently and is the same for all users.
  2. In-Memory Caching: The IMemoryCache service allows you to store data in memory within the scope of the application. This is suitable for scenarios where the data is shared among different requests within the application and is meant to be short-lived.
  3. Distributed Caching (Redis): The IDistributedCache service enables storing data in a distributed cache, like Redis. This is beneficial for scenarios where the data needs to be shared across multiple instances of the application or even across different applications in a distributed environment.

Caching, while greatly improving performance, should be used thoughtfully. Cache invalidation, data staleness, and cache eviction strategies should be considered to ensure the cached data remains accurate and up-to-date. Additionally, sensitive or private information should not be cached, and proper mechanisms must be implemented to manage cache expiration and updates.

By implementing caching techniques strategically, you can provide a faster and more responsive experience for your users while optimizing server resources and minimizing unnecessary data fetches. Remember to profile and monitor your application's performance to fine-tune your caching strategies over time.


Similar Articles