Asp.Net Core 自定义设置Http缓存处理
一、使用中间件 拦截请求自定义输出文件
输出前自定义指定响应头
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>(); } }
更多:
Http缓存机制(转)
分块编码(Transfer-Encoding: chunked)(转)
分类:
Asp.Net Core
标签:
Asp.Net Core
, 自定义设置Http缓存处理
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
2017-05-16 Asp.Net Core MVC控制器和视图之间传值