我想将 API 的响应缓存到 DistributedSqlServerCache。默认的 ResponseCaching 仅使用内存缓存。有一个构造函数允许配置要使用的缓存,但它是内部的。
我写了一个过滤器。如果响应没有被缓存,并且 http 响应是 OK 并且 ActionResult 是一个 ObjectActionResult,它会将值序列化为 JSON 并将其保存到 SQL 缓存中。如果响应被缓存,它会反序列化它并将结果设置为带有反序列化对象的 OkObject 结果。
它工作正常,但它有一些笨拙的东西(例如,要使用该属性,您必须使用 typeof() 指定将被反序列化的类型)。
有没有办法缓存对分布式 sql 缓存的响应,这不涉及我将自己的大部分工作解决方案一起破解?
另一种选择是复制-粘贴 netcore ResponseCacheMiddleWare,并修改它以使用不同的缓存。我什至可以把它做成一个 nuget 包。
还有其他解决方案吗?
这是我放在一起的过滤器(为显示目的而简化)
namespace Api.Filters
{
/// <summary>
/// Caches the result of the action as data.
/// The action result must implement <see cref="ObjectResult"/>, and is only cached if the HTTP status code is OK.
/// </summary>
public class ResponseCache : IAsyncResourceFilter
{
public Type ActionType { get; set; }
public ExpirationType ExpirationType;
private readonly IDistributedCache cache;
public ResponseCache(IDistributedCache cache)
{
this.cache = cache;
}
public async Task OnResourceExecutionAsync(ResourceExecutingContext executingContext, ResourceExecutionDelegate next)
{
var key = getKey(executingContext);
var cachedValue = await cache.GetAsync(key);
if (cachedValue != null && executingContext.HttpContext.Request.Query["r"] == "cache")
{
await cache.RemoveAsync(key);
cachedValue = null;
}
if (cachedValue != null)
{
executingContext.Result = new OkObjectResult(await fromBytes(cachedValue));
return;
}
var executedContext = await next();
// Only cache a successful response.
if (executedContext.HttpContext.Response.StatusCode == StatusCodes.Status200OK && executedContext.Result is ObjectResult result)
{
await cache.SetAsync(key, await toBytes(result.Value), getExpiration());
}
}
private async Task<byte[]> toBytes(object value)
{
using var stream = new MemoryStream();
await JsonSerializer.SerializeAsync(stream, value, ActionType);
return stream.ToArray();
}
private async Task<object> fromBytes(byte[] bytes)
{
using var stream = new MemoryStream(bytes);
using var reader = new BinaryReader(stream, Encoding.Default, true);
return await JsonSerializer.DeserializeAsync(stream, ActionType);
}
}
public class ResponseCacheAttribute : Attribute, IFilterFactory
{
public bool IsReusable => true;
public ExpirationType ExpirationType;
public Type ActionType { get; set; }
public ResponseCacheAttribute(params string[] queryParameters)
{
this.queryParameters = queryParameters;
}
public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
{
var cache = serviceProvider.GetService(typeof(IDistributedCache)) as IDistributedCache;
return new ResponseCache(cache)
{
ExpirationType = ExpirationType,
ActionType = ActionType
};
}
}
}