1、使用中間件 攔截請求自定義輸出文件html
輸出前自定義指定響應頭緩存
public class OuterImgMiddleware { public static string RootPath { get; set; } //配置文件讀取絕對位置 private readonly RequestDelegate _next; public OuterImgMiddleware(RequestDelegate next, IHostingEnvironment env) { _next = next; } public async Task Invoke(HttpContext context) { var path = context.Request.Path.ToString(); var headersDictionary = context.Request.Headers; if (context.Request.Method == "GET") if (!string.IsNullOrEmpty(path) && path.Contains("/upload/logo")) { var unauthorizedImagePath = RootPath + path; context.Response.ContentType = "image/jpeg"; context.Response.Headers["Cache-Control"] = "public"; //指定客戶端,服務器都處理緩存 int length = path.LastIndexOf(".") - path.LastIndexOf("/") - 1; context.Response.Headers["Etag"] = path.Substring(path.LastIndexOf("/") + 1, length); context.Response.Headers["Last-Modified"] = new DateTime(2018).ToString("r"); FileInfo file = new FileInfo(unauthorizedImagePath); context.Response.Headers["Content-Length"] = file.Length.ToString(); context.Response.Headers["Accept-Ranges"] = "bytes"; //若是Transfer-Encoding =chunked 沒有指定的話,SendFile 前臺解析事變 //指定Content-Length 能夠是 chunked 分塊實效 //context.Response.Headers["Transfer-Encoding"] = ""; //Http 1.0 是使用Expires 屬性 //context.Response.Headers["Expires"] = DateTime.Now.AddMonths(1).ToString("r"); await context.Response.SendFileAsync(unauthorizedImagePath); return; } await _next(context); } } public static class MvcExtensions { public static IApplicationBuilder UseOutImg(this IApplicationBuilder builder) { return builder.UseMiddleware<OuterImgMiddleware>(); } }
更多:服務器