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
``` csha
```
... <a href="/Blog/ViewPosting/17/caching-in-asp.net-core">(Weiterlesen)</a>
12/21/2022 5:09:18 PM
by Chris 931