Response and Output Caching in ASP.NET Core Print

  • 0

Caching for Better Performance

Implement caching to significantly improve your application performance on Plesk Windows hosting.

Types of Caching

  • Response Caching: Caches HTTP responses based on headers
  • Output Caching (.NET 7+): Server-side response caching with more control
  • In-Memory Caching: Cache data in application memory
  • Distributed Caching: Cache shared across servers

Response Caching

Add caching headers to HTTP responses:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCaching();

var app = builder.Build();
app.UseResponseCaching();

// In controller or minimal API
[ResponseCache(Duration = 60)]  // Cache for 60 seconds
public IActionResult GetProducts()
{
    return Ok(products);
}

Output Caching (.NET 7+)

More powerful server-side caching:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOutputCache(options =>
{
    options.AddBasePolicy(builder => builder.Expire(TimeSpan.FromMinutes(10)));
    options.AddPolicy("CacheForHour", builder => builder.Expire(TimeSpan.FromHours(1)));
});

var app = builder.Build();
app.UseOutputCache();

// Apply to endpoints
app.MapGet("/products", () => GetProducts())
   .CacheOutput("CacheForHour");

// Or with attribute
[OutputCache(Duration = 3600)]
public IActionResult GetProducts() { }

Cache Variations

Cache different responses based on query strings or headers:

options.AddPolicy("VaryByQuery", builder =>
    builder.SetVaryByQuery("category", "page")
           .Expire(TimeSpan.FromMinutes(30)));

options.AddPolicy("VaryByUser", builder =>
    builder.SetVaryByHeader("Authorization")
           .Expire(TimeSpan.FromMinutes(5)));

In-Memory Caching

builder.Services.AddMemoryCache();

// In your service
public class ProductService
{
    private readonly IMemoryCache _cache;

    public ProductService(IMemoryCache cache)
    {
        _cache = cache;
    }

    public async Task> GetProductsAsync()
    {
        return await _cache.GetOrCreateAsync("products", async entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30);
            return await _repository.GetAllAsync();
        });
    }
}

Static File Caching

Cache static files in browser:

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =>
    {
        ctx.Context.Response.Headers.Append(
            "Cache-Control", "public,max-age=31536000");
    }
});

Cache Invalidation

// Remove specific cache entry
_cache.Remove("products");

// With Output Cache
app.MapPost("/products", async (IOutputCacheStore cache) =>
{
    // Clear cache after update
    await cache.EvictByTagAsync("products", default);
});

Best Practices

  • Cache read-heavy, rarely changing data
  • Set appropriate expiration times
  • Use cache tags for easy invalidation
  • Monitor memory usage with Application Pool limits
  • Dont cache user-specific data with shared cache

Was this answer helpful?

« Back