Enhancing Performance in .NET Web API

Jul 4, 2024

Enhancing Performance in .NET Web API

Introduction

  • Host: Muhammad
  • Topic: Enhancing performance in .NET Web API
  • Techniques Covered:
    1. Response Caching
    2. In-Memory Caching

Response Caching

  • Definition: Caching the response from a single API endpoint to avoid repeated database calls and improve performance.
  • Implementation Steps:
    1. Enable Response Caching Middleware:
      • Add app.UseResponseCaching() in program.cs to include caching middleware.
    2. Set Response Cache in Controller:
      • Decorate the controller action with [ResponseCache(Duration = 60)] to cache response for 60 seconds.
  • Demo:
    • Initially returns different temperatures each time.
    • Post caching, the same response is returned for 60 seconds.

In-Memory Caching

  • Definition: Caching specific parts of a response instead of the entire response, particularly useful for partial data sets.
  • Implementation Steps:
    1. Enable In-Memory Caching:
      • Add builder.Services.AddMemoryCache() before builder.Build() in program.cs.
    2. Inject IMemoryCache in Controller:
      • Inject private readonly IMemoryCache _memoryCache and initialize in the controller’s constructor.
    3. Cache Specific Data:
      • Define a cache key (const string cacheKey = "result").
      • Check if the cache contains the key using _memoryCache.TryGetValue(cacheKey, out var forecast).
      • If not cached, set cache options (absolute expiration and sliding expiration).
      • Set cache with _memoryCache.Set(cacheKey, forecast, cacheOptions).
  • Demo:
    • Cache one part of the response while the other part updates on each request.

Conclusion

  • Benefits: Simple implementation leads to significant performance improvements.
  • Time Investment: 10-15 minutes for setup.
  • Impact: Improved user experience and API performance.

Additional Notes

  • Subscribe: Follow for more .NET on the cloud tutorials.
  • Support: Support on Patreon or buy me a coffee.
  • Queries: Leave questions in the comments.