Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created May 18, 2021 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/7623686d8a1e6ab079064dd38d411a1f to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/7623686d8a1e6ab079064dd38d411a1f to your computer and use it in GitHub Desktop.
.NET Core Applications - Startup - Static Files Middleware and Response Caching
public class Startup
{
// Some other code...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// some middlewares...
// Files from default wwwroot folder, no specific response header added.
app.UseStaticFiles();
// For images under {content-root}/Images folder
// Responses would be cached for 7 days
const string cacheMaxAge = "604800";
string imagesFolderPath = Path.Combine(env.ContentRootPath, "Images");
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(imagesFolderPath),
RequestPath = "/images",
OnPrepareResponse = ctx =>
{
// using Microsoft.AspNetCore.Http;
ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cacheMaxAge}");
}
});
// some other middlewares...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment