Skip to main content

Lesson 7 of 8

Response Compression & Caching Headers

Response compression reduces bandwidth by 60-80% for JSON APIs using Brotli or Gzip. Cache-Control headers enable browsers and CDNs to cache responses, dramatically reducing server load for static or infrequently-changing data.

15 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Compression & Cache Headers

Compression & Cache Headers
using Microsoft.AspNetCore.ResponseCompression;

// ━━ Response Compression - Brotli preferred over Gzip ━━
builder.Services.AddResponseCompression(options =>
{
    options.EnableForHttps = true;       // compress HTTPS (safe for API-only, careful with CRIME attack)
    options.Providers.Add<BrotliCompressionProvider>();
    options.Providers.Add<GzipCompressionProvider>();
    options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
        ["application/json", "application/problem+json"]);
});

builder.Services.Configure<BrotliCompressionProviderOptions>(options =>
    options.Level = System.IO.Compression.CompressionLevel.Fastest); // balance speed vs ratio

app.UseResponseCompression(); // early in pipeline

// ━━ Response Caching - Cache-Control headers ━━
builder.Services.AddResponseCaching();
app.UseResponseCaching();

// On controller actions:
[HttpGet("catalog")]
[ResponseCache(Duration = 300, VaryByQueryKeys = new[] { "category", "page" })]  // cache 5 min
public async Task<IActionResult> GetCatalog(string? category, int page = 1) => Ok();

// ━━ Manual cache header control ━━
[HttpGet("{id}")]
public async Task<IActionResult> GetProduct(string id)
{
    var product = await _repo.FindByIdAsync(id);
    if (product is null) return NotFound();

    // ETag for conditional GET - client can use If-None-Match to avoid re-downloading
    var etag = $'\"{product.UpdatedAt.Ticks}\"';

    if (Request.Headers.IfNoneMatch == etag)
        return StatusCode(304); // Not Modified - client's cache is still fresh

    Response.Headers.ETag = etag;
    Response.Headers.CacheControl = "public, max-age=60"; // cache for 60 seconds
    return Ok(product);
}

// ━━ No-cache for sensitive endpoints ━━
[HttpGet("account/balance")]
public IActionResult GetBalance()
{
    Response.Headers.CacheControl = "no-store, no-cache, must-revalidate";
    Response.Headers.Pragma = "no-cache";
    return Ok(new { Balance = 1000.00m });
}

interface IProductRepository { Task<dynamic?> FindByIdAsync(string id); }
IProductRepository _repo = null!;

Tip

Tip

Practice Response Compression Caching Headers in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Response Compression Caching Headers from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Response Compression Caching Headers is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done