
Previous article: ASP.NET Core Cloud Domination: Master Azure & AWS Global Scaling, Storage & Hosting | Production Guide (Part-25 of 40)
Table of Contents
Introduction to ASP.NET Core Performance
Understanding Performance Metrics
Async/Await Deep Dive
Entity Framework Core Performance
Caching Strategies
Response Compression
Database Optimization
Memory Management
Profiling Tools
Real-World Case Study
Advanced Performance Patterns
Monitoring and Diagnostics
Conclusion
1. Introduction to ASP.NET Core Performance
Performance is the cornerstone of modern web applications. In today's competitive digital landscape, users expect blazing-fast responses and seamless experiences. ASP.NET Core provides a robust foundation for building high-performance web applications, but mastering its performance capabilities requires a deep understanding and strategic implementation.
Why Performance Matters
User Experience: 53% of mobile users abandon sites that take longer than 3 seconds to load
Conversion Rates: A 1-second delay in page response can result in a 7% reduction in conversions
SEO Impact: Google uses page speed as a ranking factor in search results
Infrastructure Costs: Optimized applications require fewer server resources
The Performance Mindset
// Bad: Synchronous database call in controller
public IActionResult GetUser(int id)
{
var user = _context.Users.Find(id); // Blocks thread
return View(user);
}
// Good: Asynchronous database call
public async Task<IActionResult> GetUserAsync(int id)
{
var user = await _context.Users.FindAsync(id); // Non-blocking
return View(user);
}
2. Understanding Performance Metrics
Key Performance Indicators
public class PerformanceMetrics
{
// Response Time
public TimeSpan AverageResponseTime { get; set; }
public TimeSpan P95ResponseTime { get; set; }
// Throughput
public int RequestsPerSecond { get; set; }
public int ConcurrentUsers { get; set; }
// Resource Utilization
public double CpuUsage { get; set; }
public long MemoryUsage { get; set; }
public int ThreadPoolThreads { get; set; }
// Database Metrics
public int DatabaseQueriesPerRequest { get; set; }
public TimeSpan DatabaseQueryTime { get; set; }
}
Implementing Custom Metrics Middleware
public class PerformanceMonitoringMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<PerformanceMonitoringMiddleware> _logger;
public PerformanceMonitoringMiddleware(
RequestDelegate next,
ILogger<PerformanceMonitoringMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var stopwatch = Stopwatch.StartNew();
var startMemory = GC.GetTotalMemory(false);
try
{
await _next(context);
}
finally
{
stopwatch.Stop();
var endMemory = GC.GetTotalMemory(false);
var memoryUsed = endMemory - startMemory;
_logger.LogInformation(
"Request: {Method} {Path} completed in {ElapsedMs}ms using {MemoryBytes} bytes",
context.Request.Method,
context.Request.Path,
stopwatch.ElapsedMilliseconds,
memoryUsed);
// Log slow requests
if (stopwatch.ElapsedMilliseconds > 1000) // 1 second threshold
{
_logger.LogWarning(
"SLOW REQUEST: {Method} {Path} took {ElapsedMs}ms",
context.Request.Method,
context.Request.Path,
stopwatch.ElapsedMilliseconds);
}
}
}
}
// Register in Program.cs
app.UseMiddleware<PerformanceMonitoringMiddleware>();
3. Async/Await Deep Dive
Understanding the Async/Await Pattern
public class OrderService
{
private readonly IOrderRepository _orderRepository;
private readonly IPaymentService _paymentService;
private readonly IEmailService _emailService;
public OrderService(
IOrderRepository orderRepository,
IPaymentService paymentService,
IEmailService emailService)
{
_orderRepository = orderRepository;
_paymentService = paymentService;
_emailService = emailService;
}
// Synchronous version - AVOID THIS
public OrderResult ProcessOrderSync(OrderRequest request)
{
// 1. Validate order (CPU-bound)
var validationResult = ValidateOrder(request);
if (!validationResult.IsValid)
return OrderResult.Failure(validationResult.Errors);
// 2. Process payment (I/O-bound - BLOCKING!)
var paymentResult = _paymentService.ProcessPayment(request.Payment);
if (!paymentResult.Success)
return OrderResult.Failure("Payment failed");
// 3. Create order in database (I/O-bound - BLOCKING!)
var order = _orderRepository.Create(request);
// 4. Send confirmation email (I/O-bound - BLOCKING!)
_emailService.SendConfirmation(order);
return OrderResult.Success(order);
}
// Asynchronous version - USE THIS
public async Task<OrderResult> ProcessOrderAsync(OrderRequest request)
{
// 1. Validate order (still synchronous - CPU-bound)
var validationResult = ValidateOrder(request);
if (!validationResult.IsValid)
return OrderResult.Failure(validationResult.Errors);
// 2. Process payment (I/O-bound - NON-BLOCKING!)
var paymentResult = await _paymentService.ProcessPaymentAsync(request.Payment);
if (!paymentResult.Success)
return OrderResult.Failure("Payment failed");
// 3. Create order in database (I/O-bound - NON-BLOCKING!)
var order = await _orderRepository.CreateAsync(request);
// 4. Send confirmation email (I/O-bound - NON-BLOCKING!)
// Fire and forget - don't await if not critical
_ = Task.Run(() => _emailService.SendConfirmationAsync(order));
return OrderResult.Success(order);
}
// Advanced: Parallel async operations
public async Task<OrderResult> ProcessOrderParallelAsync(OrderRequest request)
{
var validationResult = ValidateOrder(request);
if (!validationResult.IsValid)
return OrderResult.Failure(validationResult.Errors);
// Start multiple async operations
var paymentTask = _paymentService.ProcessPaymentAsync(request.Payment);
var inventoryTask = _inventoryService.ReserveItemsAsync(request.Items);
// Wait for all to complete
await Task.WhenAll(paymentTask, inventoryTask);
if (!paymentTask.Result.Success)
return OrderResult.Failure("Payment failed");
if (!inventoryTask.Result.Success)
return OrderResult.Failure("Inventory reservation failed");
var order = await _orderRepository.CreateAsync(request);
return OrderResult.Success(order);
}
}
Common Async/Await Pitfalls and Solutions
public class AsyncAntiPatterns
{
// 1. Async Void - AVOID (except event handlers)
public async void BadMethodAsync()
{
await Task.Delay(1000);
// Exceptions can't be caught properly!
}
// 2. Blocking Async Code - AVOID
public void BadBlocking()
{
var result = SomeAsyncMethod().Result; // Can cause deadlocks
var result2 = SomeAsyncMethod().GetAwaiter().GetResult(); // Still bad
}
// 3. ConfigureAwait False - USE CAREFULLY
public async Task GoodAsyncMethod()
{
await SomeAsyncOperation().ConfigureAwait(false);
// After this point, we might not be on the original context
}
// 4. Excessive Async - DON'T OVERUSE
public Task<int> CalculateSyncOperation()
{
// This is CPU-bound work - don't make it async
var result = HeavyCalculation();
return Task.FromResult(result); // Wrap in task if interface requires it
}
// 5. Proper cancellation support
public async Task<string> DownloadWithTimeoutAsync(
string url,
CancellationToken cancellationToken = default)
{
using var client = new HttpClient();
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken, timeoutCts.Token);
try
{
var response = await client.GetAsync(url, linkedCts.Token);
return await response.Content.ReadAsStringAsync();
}
catch (OperationCanceledException)
{
throw new TimeoutException("Download timed out");
}
}
}
Real-World Async Controller Example
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly IProductService _productService;
private readonly IImageService _imageService;
private readonly ICacheService _cacheService;
public ProductsController(
IProductService productService,
IImageService imageService,
ICacheService cacheService)
{
_productService = productService;
_imageService = imageService;
_cacheService = cacheService;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetProduct(int id)
{
// Cache-aside pattern with async
var cacheKey = $"product_{id}";
var product = await _cacheService.GetAsync<Product>(cacheKey);
if (product == null)
{
product = await _productService.GetProductAsync(id);
if (product != null)
{
await _cacheService.SetAsync(cacheKey, product, TimeSpan.FromMinutes(30));
}
}
return product != null ? Ok(product) : NotFound();
}
[HttpPost]
public async Task<IActionResult> CreateProduct([FromForm] ProductCreateRequest request)
{
// Process image upload asynchronously
if (request.Image != null)
{
var imageUrl = await _imageService.UploadImageAsync(request.Image);
request.ImageUrl = imageUrl;
}
// Save product to database
var product = await _productService.CreateProductAsync(request);
// Invalidate related cache entries
await _cacheService.RemoveAsync("products_list");
await _cacheService.RemoveAsync($"category_{product.CategoryId}_products");
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
[HttpGet("search")]
public async Task<IActionResult> SearchProducts(
[FromQuery] string query,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20,
CancellationToken cancellationToken = default)
{
// Parallel async operations for better performance
var searchTask = _productService.SearchProductsAsync(query, page, pageSize, cancellationToken);
var filtersTask = _productService.GetSearchFiltersAsync(query, cancellationToken);
await Task.WhenAll(searchTask, filtersTask);
var result = new SearchResult
{
Products = await searchTask,
Filters = await filtersTask,
Page = page,
TotalResults = await _productService.GetSearchCountAsync(query, cancellationToken)
};
return Ok(result);
}
}
4. Entity Framework Core Performance
Efficient Query Patterns
public class EfficientProductService
{
private readonly ApplicationDbContext _context;
public EfficientProductService(ApplicationDbContext context)
{
_context = context;
}
// BAD: N+1 Query Problem
public async Task<List<ProductDto>> GetProductsBadAsync(int categoryId)
{
var products = await _context.Products
.Where(p => p.CategoryId == categoryId)
.ToListAsync();
var result = new List<ProductDto>();
foreach (var product in products)
{
// BAD: Separate query for each product's category
var category = await _context.Categories
.FirstOrDefaultAsync(c => c.Id == product.CategoryId);
result.Add(new ProductDto
{
Id = product.Id,
Name = product.Name,
CategoryName = category.Name // N+1 problem!
});
}
return result;
}
// GOOD: Eager Loading with Include
public async Task<List<ProductDto>> GetProductsGoodAsync(int categoryId)
{
var products = await _context.Products
.Where(p => p.CategoryId == categoryId)
.Include(p => p.Category) // Single query with JOIN
.Include(p => p.Supplier)
.Select(p => new ProductDto
{
Id = p.Id,
Name = p.Name,
CategoryName = p.Category.Name, // Already loaded
SupplierName = p.Supplier.Name,
Price = p.Price
})
.AsNoTracking() // Read-only query - no change tracking
.ToListAsync();
return products;
}
// BETTER: Projection (Select) only needed fields
public async Task<List<ProductSummaryDto>> GetProductsProjectionAsync(int categoryId)
{
return await _context.Products
.Where(p => p.CategoryId == categoryId)
.Select(p => new ProductSummaryDto
{
Id = p.Id,
Name = p.Name,
Price = p.Price,
CategoryName = p.Category.Name,
IsInStock = p.StockQuantity > 0
})
.AsNoTracking()
.ToListAsync();
}
// EXCELLENT: Compiled Queries for frequently used queries
private static readonly Func<ApplicationDbContext, int, Task<List<ProductSummaryDto>>>
GetProductsByCategoryQuery =
EF.CompileAsyncQuery(
(ApplicationDbContext context, int categoryId) =>
context.Products
.Where(p => p.CategoryId == categoryId)
.Select(p => new ProductSummaryDto
{
Id = p.Id,
Name = p.Name,
Price = p.Price,
CategoryName = p.Category.Name
})
.AsNoTracking()
.ToList());
public Task<List<ProductSummaryDto>> GetProductsCompiledAsync(int categoryId)
{
return GetProductsByCategoryQuery(_context, categoryId);
}
}
Bulk Operations and Batch Processing
public class BulkOperationsService
{
private readonly ApplicationDbContext _context;
public BulkOperationsService(ApplicationDbContext context)
{
_context = context;
}
// BAD: Individual inserts - SLOW
public async Task ImportProductsBadAsync(List<ProductImportDto> products)
{
foreach (var productDto in products)
{
var product = new Product
{
Name = productDto.Name,
Price = productDto.Price,
CategoryId = productDto.CategoryId,
CreatedAt = DateTime.UtcNow
};
_context.Products.Add(product);
await _context.SaveChangesAsync(); // BAD: Save after each insert
}
}
// GOOD: Batch insert
public async Task ImportProductsGoodAsync(List<ProductImportDto> products)
{
var entities = products.Select(p => new Product
{
Name = p.Name,
Price = p.Price,
CategoryId = p.CategoryId,
CreatedAt = DateTime.UtcNow
}).ToList();
_context.Products.AddRange(entities);
await _context.SaveChangesAsync(); // Single database roundtrip
}
// BETTER: Bulk Extensions for large datasets
public async Task ImportProductsBulkAsync(List<ProductImportDto> products)
{
var entities = products.Select(p => new Product
{
Name = p.Name,
Price = p.Price,
CategoryId = p.CategoryId,
CreatedAt = DateTime.UtcNow
}).ToList();
// Using third-party bulk extensions (e.g., EFCore.BulkExtensions)
await _context.BulkInsertAsync(entities, new BulkConfig
{
BatchSize = 1000,
UseTempDB = true
});
}
// Efficient bulk updates
public async Task UpdateProductPricesAsync(int categoryId, decimal percentageIncrease)
{
// Single UPDATE statement
await _context.Products
.Where(p => p.CategoryId == categoryId)
.ExecuteUpdateAsync(p => p
.SetProperty(x => x.Price, x => x.Price * (1 + percentageIncrease / 100))
.SetProperty(x => x.UpdatedAt, DateTime.UtcNow));
}
// Efficient bulk deletes
public async Task DeleteOldProductsAsync(DateTime olderThan)
{
// Single DELETE statement
await _context.Products
.Where(p => p.CreatedAt < olderThan)
.ExecuteDeleteAsync();
}
}
DbContext Pooling and Configuration
public static class DatabaseConfiguration
{
public static void ConfigureDatabase(IServiceCollection services, IConfiguration configuration)
{
// Regular DbContext registration
// services.AddDbContext<ApplicationDbContext>(options =>
// options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
// DbContext Pooling for better performance
services.AddDbContextPool<ApplicationDbContext>(options =>
{
options.UseSqlServer(
configuration.GetConnectionString("DefaultConnection"),
sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(
maxRetryCount: 3,
maxRetryDelay: TimeSpan.FromSeconds(5),
errorNumbersToAdd: null);
sqlOptions.CommandTimeout(30);
});
// Enable sensitive data logging only in development
if (Environment.IsDevelopment())
{
options.EnableSensitiveDataLogging();
options.EnableDetailedErrors();
}
});
// Query splitting configuration for complex queries
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(
configuration.GetConnectionString("DefaultConnection"),
options => options.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
});
}
}
// Optimized DbContext design
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
// Performance optimizations
ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
ChangeTracker.AutoDetectChangesEnabled = false;
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
// Auto-detect changes before save
ChangeTracker.DetectChanges();
// Set audit fields
var entries = ChangeTracker.Entries()
.Where(e => e.Entity is IAuditable &&
(e.State == EntityState.Added || e.State == EntityState.Modified));
foreach (var entry in entries)
{
var entity = (IAuditable)entry.Entity;
if (entry.State == EntityState.Added)
{
entity.CreatedAt = DateTime.UtcNow;
entity.CreatedBy = "system"; // Get from current user in real scenario
}
entity.UpdatedAt = DateTime.UtcNow;
entity.UpdatedBy = "system";
}
return await base.SaveChangesAsync(cancellationToken);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Configure indexes for better query performance
modelBuilder.Entity<Product>()
.HasIndex(p => p.CategoryId)
.IncludeProperties(p => new { p.Name, p.Price, p.IsActive });
modelBuilder.Entity<Product>()
.HasIndex(p => new { p.Name, p.IsActive });
// Configure decimal precision
modelBuilder.Entity<Product>()
.Property(p => p.Price)
.HasPrecision(18, 2);
// Configure relationships and delete behavior
modelBuilder.Entity<Product>()
.HasOne(p => p.Category)
.WithMany(c => c.Products)
.HasForeignKey(p => p.CategoryId)
.OnDelete(DeleteBehavior.Restrict);
}
}
5. Caching Strategies
Multi-Level Caching Implementation
public interface ICacheService
{
Task<T> GetAsync<T>(string key);
Task SetAsync<T>(string key, T value, TimeSpan? expiry = null);
Task RemoveAsync(string key);
Task<bool> ExistsAsync(string key);
}
public class DistributedCacheService : ICacheService
{
private readonly IDistributedCache _cache;
private readonly ILogger<DistributedCacheService> _logger;
public DistributedCacheService(
IDistributedCache cache,
ILogger<DistributedCacheService> logger)
{
_cache = cache;
_logger = logger;
}
public async Task<T> GetAsync<T>(string key)
{
try
{
var cachedData = await _cache.GetStringAsync(key);
if (cachedData == null)
{
_logger.LogDebug("Cache miss for key: {Key}", key);
return default;
}
_logger.LogDebug("Cache hit for key: {Key}", key);
return JsonSerializer.Deserialize<T>(cachedData);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error reading from cache for key: {Key}", key);
return default; // Fail gracefully
}
}
public async Task SetAsync<T>(string key, T value, TimeSpan? expiry = null)
{
try
{
var serializedData = JsonSerializer.Serialize(value);
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = expiry ?? TimeSpan.FromMinutes(30)
};
await _cache.SetStringAsync(key, serializedData, options);
_logger.LogDebug("Cache set for key: {Key} with expiry: {Expiry}", key, expiry);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error writing to cache for key: {Key}", key);
}
}
public async Task RemoveAsync(string key)
{
try
{
await _cache.RemoveAsync(key);
_logger.LogDebug("Cache removed for key: {Key}", key);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error removing from cache for key: {Key}", key);
}
}
public async Task<bool> ExistsAsync(string key)
{
var data = await _cache.GetStringAsync(key);
return data != null;
}
}
// Advanced caching with memory cache fallback
public class MultiLevelCacheService : ICacheService
{
private readonly IDistributedCache _distributedCache;
private readonly IMemoryCache _memoryCache;
private readonly ILogger<MultiLevelCacheService> _logger;
public MultiLevelCacheService(
IDistributedCache distributedCache,
IMemoryCache memoryCache,
ILogger<MultiLevelCacheService> logger)
{
_distributedCache = distributedCache;
_memoryCache = memoryCache;
_logger = logger;
}
public async Task<T> GetAsync<T>(string key)
{
// First, try memory cache (L1)
if (_memoryCache.TryGetValue(key, out T memoryCachedValue))
{
_logger.LogDebug("L1 cache hit for key: {Key}", key);
return memoryCachedValue;
}
// Then, try distributed cache (L2)
try
{
var distributedValue = await _distributedCache.GetStringAsync(key);
if (distributedValue != null)
{
var value = JsonSerializer.Deserialize<T>(distributedValue);
// Populate L1 cache
_memoryCache.Set(key, value, TimeSpan.FromMinutes(5));
_logger.LogDebug("L2 cache hit for key: {Key}", key);
return value;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error reading from distributed cache for key: {Key}", key);
}
_logger.LogDebug("Cache miss for key: {Key}", key);
return default;
}
public async Task SetAsync<T>(string key, T value, TimeSpan? expiry = null)
{
var actualExpiry = expiry ?? TimeSpan.FromMinutes(30);
// Set in memory cache with shorter expiry
_memoryCache.Set(key, value, TimeSpan.FromMinutes(5));
// Set in distributed cache
try
{
var serializedData = JsonSerializer.Serialize(value);
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = actualExpiry
};
await _distributedCache.SetStringAsync(key, serializedData, options);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error writing to distributed cache for key: {Key}", key);
}
}
public async Task RemoveAsync(string key)
{
// Remove from both caches
_memoryCache.Remove(key);
try
{
await _distributedCache.RemoveAsync(key);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error removing from distributed cache for key: {Key}", key);
}
}
public async Task<bool> ExistsAsync(string key)
{
return _memoryCache.TryGetValue(key, out _) ||
await _distributedCache.GetStringAsync(key) != null;
}
}
Cache-Aside Pattern with Stampede Protection
public class CacheAsideService
{
private readonly ICacheService _cache;
private readonly ILogger<CacheAsideService> _logger;
private readonly ConcurrentDictionary<string, SemaphoreSlim> _locks;
public CacheAsideService(ICacheService cache, ILogger<CacheAsideService> logger)
{
_cache = cache;
_logger = logger;
_locks = new ConcurrentDictionary<string, SemaphoreSlim>();
}
public async Task<T> GetOrSetAsync<T>(
string key,
Func<Task<T>> factory,
TimeSpan? expiry = null)
{
// Try to get from cache first
var cachedValue = await _cache.GetAsync<T>(key);
if (cachedValue != null)
{
return cachedValue;
}
// Cache miss - acquire lock for this key to prevent cache stampede
var lockKey = $"{key}_lock";
var lockObj = _locks.GetOrAdd(lockKey, _ => new SemaphoreSlim(1, 1));
await lockObj.WaitAsync();
try
{
// Double-check after acquiring lock
cachedValue = await _cache.GetAsync<T>(key);
if (cachedValue != null)
{
return cachedValue;
}
// Generate value using factory
_logger.LogInformation("Cache miss - generating value for key: {Key}", key);
var value = await factory();
// Set in cache
if (value != null)
{
await _cache.SetAsync(key, value, expiry);
}
return value;
}
finally
{
lockObj.Release();
_locks.TryRemove(lockKey, out _);
}
}
}
// Real-world usage example
public class ProductServiceWithCache
{
private readonly ApplicationDbContext _context;
private readonly CacheAsideService _cacheService;
public ProductServiceWithCache(
ApplicationDbContext context,
CacheAsideService cacheService)
{
_context = context;
_cacheService = cacheService;
}
public async Task<Product> GetProductAsync(int id)
{
var cacheKey = $"product_{id}";
return await _cacheService.GetOrSetAsync(
cacheKey,
async () => await _context.Products
.Include(p => p.Category)
.Include(p => p.Supplier)
.AsNoTracking()
.FirstOrDefaultAsync(p => p.Id == id),
TimeSpan.FromMinutes(30));
}
public async Task<List<Product>> GetProductsByCategoryAsync(int categoryId)
{
var cacheKey = $"products_category_{categoryId}";
return await _cacheService.GetOrSetAsync(
cacheKey,
async () => await _context.Products
.Where(p => p.CategoryId == categoryId && p.IsActive)
.Include(p => p.Category)
.AsNoTracking()
.ToListAsync(),
TimeSpan.FromMinutes(15));
}
}
Response Caching Middleware
// Custom response cache attribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomResponseCacheAttribute : Attribute, IAsyncActionFilter
{
private readonly int _duration;
private readonly ResponseCacheLocation _location;
private readonly bool _varyByQuery;
public CustomResponseCacheAttribute(
int durationInSeconds,
ResponseCacheLocation location = ResponseCacheLocation.Any,
bool varyByQuery = true)
{
_duration = durationInSeconds;
_location = location;
_varyByQuery = varyByQuery;
}
public async Task OnActionExecutionAsync(
ActionExecutingContext context,
ActionExecutionDelegate next)
{
var executedContext = await next();
if (executedContext.Result is ObjectResult objectResult &&
objectResult.StatusCode == 200)
{
var response = context.HttpContext.Response;
response.GetTypedHeaders().CacheControl = new CacheControlHeaderValue
{
Public = _location == ResponseCacheLocation.Any,
Private = _location == ResponseCacheLocation.Client,
MaxAge = TimeSpan.FromSeconds(_duration),
MustRevalidate = true
};
// Add custom cache headers
response.Headers[HeaderNames.Vary] = _varyByQuery ? "Accept-Encoding,Accept" : "Accept-Encoding";
response.Headers["X-Cache-Info"] = $"max-age={_duration}, public";
}
}
}
// Usage in controllers
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet("{id}")]
[CustomResponseCache(300)] // Cache for 5 minutes
public async Task<IActionResult> GetProduct(int id)
{
// Implementation
}
[HttpGet("search")]
[CustomResponseCache(60, varyByQuery: true)] // Cache for 1 minute, vary by query
public async Task<IActionResult> SearchProducts([FromQuery] string query)
{
// Implementation
}
}
// Configure response caching in Program.cs
builder.Services.AddResponseCaching(options =>
{
options.MaximumBodySize = 1024 * 1024; // 1MB
options.UseCaseSensitivePaths = false;
});
app.UseResponseCaching();
6. Response Compression
Compression Middleware Configuration
public static class CompressionConfiguration
{
public static void ConfigureCompression(IServiceCollection services)
{
services.Configure<BrotliCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Fastest;
});
services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Optimal;
});
services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
// Add custom MIME types
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[]
{
"image/svg+xml",
"application/octet-stream",
"application/wasm"
});
// Skip compression for small responses
options.ExcludedPaths.Add("/small-endpoint");
});
}
}
// Custom compression provider for specific content
public class CustomCompressionProvider : ICompressionProvider
{
private readonly ICompressionProvider _innerProvider;
public CustomCompressionProvider(ICompressionProvider innerProvider)
{
_innerProvider = innerProvider;
}
public Stream CreateStream(Stream outputStream)
{
return _innerProvider.CreateStream(outputStream);
}
public Stream CreateStream(Stream outputStream, CompressionLevel level)
{
return _innerProvider.CreateStream(outputStream, level);
}
}
Dynamic Compression Strategies
public class CompressionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<CompressionMiddleware> _logger;
public CompressionMiddleware(
RequestDelegate next,
ILogger<CompressionMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var originalBodyStream = context.Response.Body;
try
{
// Check if compression should be applied
if (ShouldCompressResponse(context))
{
var compressionProvider = GetCompressionProvider(context);
if (compressionProvider != null)
{
using var memoryStream = new MemoryStream();
context.Response.Body = memoryStream;
await _next(context);
// Check response size and content type
if (ShouldCompressBasedOnContent(context, memoryStream))
{
await CompressResponseAsync(
context, memoryStream, originalBodyStream, compressionProvider);
return;
}
else
{
// Copy uncompressed response
memoryStream.Seek(0, SeekOrigin.Begin);
await memoryStream.CopyToAsync(originalBodyStream);
return;
}
}
}
// Continue without compression
await _next(context);
}
finally
{
context.Response.Body = originalBodyStream;
}
}
private bool ShouldCompressResponse(HttpContext context)
{
// Skip compression for certain paths
var path = context.Request.Path.Value ?? "";
if (path.Contains("/no-compress/") || path.EndsWith(".jpg") || path.EndsWith(".png"))
{
return false;
}
// Check if client supports compression
var acceptEncoding = context.Request.Headers.AcceptEncoding.ToString();
return acceptEncoding.Contains("br") || acceptEncoding.Contains("gzip");
}
private ICompressionProvider GetCompressionProvider(HttpContext context)
{
var acceptEncoding = context.Request.Headers.AcceptEncoding.ToString();
if (acceptEncoding.Contains("br"))
{
return context.RequestServices.GetService<BrotliCompressionProvider>();
}
else if (acceptEncoding.Contains("gzip"))
{
return context.RequestServices.GetService<GzipCompressionProvider>();
}
return null;
}
private bool ShouldCompressBasedOnContent(HttpContext context, MemoryStream stream)
{
// Don't compress very small responses
if (stream.Length < 1024) // 1KB
{
return false;
}
// Check content type
var contentType = context.Response.ContentType ?? "";
var compressibleTypes = new[]
{
"text/plain", "text/html", "text/css", "application/javascript",
"application/json", "application/xml", "text/xml"
};
return compressibleTypes.Any(t => contentType.StartsWith(t));
}
private async Task CompressResponseAsync(
HttpContext context,
MemoryStream sourceStream,
Stream destinationStream,
ICompressionProvider compressionProvider)
{
sourceStream.Seek(0, SeekOrigin.Begin);
using var compressionStream = compressionProvider.CreateStream(destinationStream);
// Set appropriate content encoding header
if (compressionProvider is BrotliCompressionProvider)
{
context.Response.Headers.ContentEncoding = "br";
}
else if (compressionProvider is GzipCompressionProvider)
{
context.Response.Headers.ContentEncoding = "gzip";
}
// Remove content length header since it will change
context.Response.Headers.ContentLength = null;
await sourceStream.CopyToAsync(compressionStream);
await compressionStream.FlushAsync();
_logger.LogDebug(
"Compressed response from {OriginalSize} to {CompressedSize} bytes",
sourceStream.Length, compressionStream.Length);
}
}

Join the conversation! Your thoughts help the community grow.