using Common.Tools; using Common.Utilities; using djy_AfrApi.Attributes; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Controllers; using Newtonsoft.Json; using System.IO; using System.Threading.Tasks; namespace djy_AfrApi.Milldlewares { public class CommonDataCacheMiddleware { private readonly RequestDelegate next; public CommonDataCacheMiddleware(RequestDelegate next) { this.next = next; } public async Task InvokeAsync(HttpContext context) { var endpoint = context.GetEndpoint(); if (endpoint?.Metadata?.GetMetadata() == null) { await next(context); } else { var actionDescriptor = endpoint.Metadata.GetMetadata(); if (actionDescriptor?.ActionName == null) { await next(context); } else { string redisKey = actionDescriptor.ActionName + "Cache"; string cacheData = YsRedisHelp.RedisGetString(redisKey); if (string.IsNullOrEmpty(cacheData)) { // 存储响应数据 using (MemoryStream memoryStream = new MemoryStream()) { // 使用自定义的响应流,将所有写入重定向到内存流 var originalBodyStream = context.Response.Body; context.Response.Body = memoryStream; try { await next(context); // 从内存流读取响应内容 memoryStream.Seek(0, SeekOrigin.Begin); string responseBody = new StreamReader(memoryStream).ReadToEnd(); Response response = JsonConvert.DeserializeObject(responseBody); if (response.Code == 200) { YsRedisHelp.RedisSet(redisKey, responseBody, 86400); } // 将响应内容写回原始响应流 memoryStream.Seek(0, SeekOrigin.Begin); await memoryStream.CopyToAsync(originalBodyStream); } finally { // 恢复原始响应流 context.Response.Body = originalBodyStream; } } } else { context.Response.ContentType = "application/json"; await context.Response.WriteAsync(cacheData).ConfigureAwait(false); } } } } } }