一、使用中间件 拦截请求自定义输出文件

输出前自定义指定响应头


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>();         }     }



 ​