Created
May 18, 2021 20:45
-
-
Save manoj-choudhari-git/7623686d8a1e6ab079064dd38d411a1f to your computer and use it in GitHub Desktop.
.NET Core Applications - Startup - Static Files Middleware and Response Caching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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