In this lesson, you will learn how to offload static file delivery from your .NET application to a Content Delivery Network (CDN) to reduce latency and server resource consumption.
Why Offload Static Content?
When your .NET service serves images, CSS, or JavaScript files directly from the local file system or a web-root folder, every request consumes CPU and memory. Furthermore, the round-trip time for a user in Tokyo to download a static file from a server hosted in New York is significantly high. By using a CDN, we cache these assets on geographically distributed edge locations. When a user requests a file, the edge server closest to them handles the request, completely bypassing your .NET service.
Implementation Strategy
To offload these assets, you should update your application to point to the CDN endpoint rather than local paths. In an ASP.NET Core environment, you can use a base URL configuration to switch between local development and CDN production environments.
First, define your CDN base URL in your appsettings.json:
{
"StaticAssets": {
"BaseUrl": "https://cdn.example.com"
}
}
Then, create a helper or use a tag helper to resolve the path:
public string GetAssetPath(string fileName)
{
var baseUrl = _configuration["StaticAssets:BaseUrl"];
return $"{baseUrl}/assets/{fileName}";
}
Cache Headers and Invalidation
For this to work effectively, ensure your build pipeline sets appropriate Cache-Control headers for static files (e.g., max-age=31536000, immutable). When you deploy a new version of your .NET service, you must use cache busting—typically by appending a hash or version string to your filenames (e.g., styles.v2.css). This ensures that the edge locations fetch the latest version of your assets instead of serving stale content from their local cache.
By pushing your assets to a Blob Storage or an S3 bucket that acts as an origin for your CDN, you decouple your static assets from your deployment lifecycle, allowing your .NET service to focus solely on dynamic API responses.
Key Takeaway: Offloading static assets to a CDN improves global performance by serving content from the edge, freeing your .NET services from the overhead of static file delivery.