You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
3.1 KiB
C#

11 months ago
using Common.Tools;
using Common.Utilities;
11 months ago
using djy_AfrApi.Attributes;
11 months ago
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Newtonsoft.Json;
using System.IO;
using System.Threading.Tasks;
namespace djy_AfrApi.Milldlewares
{
11 months ago
public class CommonDataCacheMiddleware
11 months ago
{
private readonly RequestDelegate next;
11 months ago
public CommonDataCacheMiddleware(RequestDelegate next)
11 months ago
{
this.next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var endpoint = context.GetEndpoint();
if (endpoint?.Metadata?.GetMetadata<RedisCachingAttribute>() == null)
{
await next(context);
}
else
{
var actionDescriptor = endpoint.Metadata.GetMetadata<ControllerActionDescriptor>();
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<Response>(responseBody);
if (response.Code == 200)
{
YsRedisHelp.RedisSet<string>(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);
}
}
}
}
}
}