Asp.net-Core
如何將 css、js 或圖像文件記憶體到 asp.net 核心
間歇性代理導致我的頁面被我部署的 asp.net 核心站點記憶體。Web 伺服器沒有記憶體頁面。
我添加了請求和響應記憶體以防止此代理導致的任何記憶體
在我的
Startup.csapp.UseStaticFiles(); app.UseIdentity(); app.Use(async (context, next) => { context.Response.Headers.Append("Cache-Control", "no-cache"); context.Response.Headers.Append("Cache-Control", "private, no-store"); context.Request.Headers.Append("Cache-Control", "no-cache"); context.Request.Headers.Append("Cache-Control", "private, no-store"); await next(); });我可以在提琴手中看到這些沒有記憶體標頭已添加到我的頁面以及 javascript 文件、css 文件和圖像文件中。
- 如何將此無記憶體標頭限制為僅適用於 asp.net mvc 頁面,以便這些無記憶體標頭不會出現在提琴手中,用於 js、css 和圖像文件等非頁面文件
- 有沒有辦法讓對 css 和 js 文件的 HTTP 請求不檢查每個請求的伺服器上是否存在該文件,而只是使用瀏覽器版本來第一次獲取這些文件。我問的原因是,在重負載(1000 個使用者)時,我在 Fiddler 中註意到我的 css、js 和圖像文件的 HTTPGET 出現 404 錯誤,因此我試圖限制對這些資源的請求數量。當請求成功(未載入)時,我得到 304 響應(未修改)。有沒有辦法告訴瀏覽器首先不要發出請求並使用本地記憶體版本。
這是一種適合您的方法。此範例將 css 和 js 文件設置為由瀏覽器記憶體 7 天,並將非 css、js 和圖像設置為沒有記憶體頭。另一個注意事項是,只需要在響應上設置記憶體控制標頭是 Asp.NET Core。
app.Use(async (context, next) => { string path = context.Request.Path; if(path.EndsWith(".css") || path.EndsWith(".js")) { //Set css and js files to be cached for 7 days TimeSpan maxAge = new TimeSpan(7, 0, 0, 0); //7 days context.Response.Headers.Append("Cache-Control", "max-age="+ maxAge.TotalSeconds.ToString("0")); } else if(path.EndsWith(".gif") || path.EndsWith(".jpg") || path.EndsWith(".png")) { //custom headers for images goes here if needed } else { //Request for views fall here. context.Response.Headers.Append("Cache-Control", "no-cache"); context.Response.Headers.Append("Cache-Control", "private, no-store"); } await next(); });
app.UseStaticFiles(new StaticFileOptions() { OnPrepareResponse = r => { string path = r.File.PhysicalPath; if (path.EndsWith(".css") || path.EndsWith(".js") || path.EndsWith(".gif") || path.EndsWith(".jpg") || path.EndsWith(".png") || path.EndsWith(".svg")) { TimeSpan maxAge = new TimeSpan(7, 0, 0, 0); r.Context.Response.Headers.Append("Cache-Control", "max-age=" + maxAge.TotalSeconds.ToString("0")); } } });