fixes for caching

This commit is contained in:
Hamid Reza Mohammadi 2026-09-01 16:14:47 +03:30
parent bf38bb5230
commit 11a085efb3

View File

@ -1,8 +1,11 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using System;
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Unicode;
@ -89,7 +92,36 @@ namespace GanjooRazor
app.UseStatusCodePagesWithReExecute("/errors/{0}");
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
var path = ctx.Context.Request.Path.Value ?? "";
var isExplicitlyVersioned = ctx.Context.Request.Query.ContainsKey("version") ||
ctx.Context.Request.Query.ContainsKey("v");
// /lib and /dist are third-party vendor code (jQuery, Bootstrap, TinyMCE, diff.js,
// the jPlayer skin) that isn't hand-edited, so it's safe to treat the same as
// explicitly-versioned assets even without a query string.
var isVendorPath = path.StartsWith("/lib/", StringComparison.OrdinalIgnoreCase) ||
path.StartsWith("/dist/", StringComparison.OrdinalIgnoreCase);
var headers = ctx.Context.Response.GetTypedHeaders();
headers.CacheControl = new CacheControlHeaderValue
{
Public = true,
// Versioned (?version=N / ?v=N) and vendor assets: the URL itself changes
// whenever the content does, so a year-long cache is safe and is what should
// eliminate most of the repeated p8.css/bk.js/user-panel.css/js downloads seen
// in the IIS logs.
// Everything else: no version query to rely on, so a conservative 6-hour cache
// still cuts a lot of redundant requests without risking long-lived staleness
// if someone edits chart.js/r2.js/etc. without remembering to bump a version.
MaxAge = (isExplicitlyVersioned || isVendorPath)
? TimeSpan.FromDays(365)
: TimeSpan.FromHours(6)
};
}
});
app.UseRouting();