Caching in ASP.NET Core

12/21/2022 5:09:18 PM by Chris 675
Quellen: * https://andrewlock.net/adding-cache-control-headers-to-static-files-in-asp-net-core/ * https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-7.0 * https://stackoverflow.com/questions/37706370/how-to-cache-css-js-or-images-files-to-asp-net-core Heute hab ich ein wenig Caching in den Blog eingebaut, als Inspiration hatte ich die Links oben. Zuerst wird die Program.cs angepasst ``` csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddResponseCaching(); var app = builder.Build(); app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = ctx => { string path = ctx.File.Name.ToLower(); if (path.EndsWith(".css") || path.EndsWith(".js") || path.EndsWith(".gif") || path.EndsWith(".jpg") || path.EndsWith(".png") || path.EndsWith(".ico") || path.EndsWith(".woff2") || path.Contains("/blog/getimage/")) { var maxAge = new TimeSpan(7, 0, 0, 0); ctx.Context.Response.Headers.Append("Cache-Control", "max-age=" + maxAge.TotalSeconds.ToString("0")); } else { //Request for views fall here. ctx.Context.Response.Headers.Append("Cache-Control", "no-cache"); ctx.Context.Response.Headers.Append("Cache-Control", "private, no-store"); } } }); ``` Und nun pass wir wir noch die GetImage Funktion an ``` csharp [HttpGet] [ResponseCache(VaryByQueryKeys = new string[] { "w", "h" }, Duration = 604800)] public IActionResult GetImage(int id, int w, int h) { [...] if (System.IO.File.Exists(webHostEnvironment.WebRootPath + fileWithRes)) { DateTimeOffset last = System.IO.File.GetLastWriteTime(webHostEnvironment.WebRootPath + fileWithRes); // Truncate to the second. var _lastModified = new DateTimeOffset(last.Year, last.Month, last.Day, last.Hour, last.Minute, last.Second, last.Offset).ToUniversalTime(); var _length = System.IO.File.ReadAllBytes(webHostEnvironment.WebRootPath + fileWithRes).Length; var etagHash = _lastModified.ToFileTime() ^ _length; var _etag = new Microsoft.Net.Http.Headers.EntityTagHeaderValue('\"' + Convert.ToString(etagHash, 16) + '\"'); return File(virtualPath: fileWithRes, contentType: "image/jpeg", lastModified: last, entityTag: _etag); } ``` Erklärungen gibt es in den Links :)


About author

Chris

Moin, hier sollte ein Text über mich stehen, ggf reiche ich den noch nach, ggf nicht. Manchmal ist es doch auch ganz schön keine Infos über einen Author zu haben :-)


Scroll to Top