我在我已经开发的应用程序中使用新的.NET 7 OutputCache。这是我添加 OutputCache 的方法。
builder.Services.AddOutputCache(x => x.AddPolicy("default", new CustomCachePolicy()));
app.UseOutputCache();
internal class CustomCachePolicy : IOutputCachePolicy {
public ValueTask CacheRequestAsync(OutputCacheContext context, CancellationToken cancellation) {
context.AllowCacheLookup = true;
context.AllowCacheStorage = true;
context.AllowLocking = true;
context.EnableOutputCaching = true;
context.ResponseExpirationTimeSpan = TimeSpan.FromSeconds(10);
return ValueTask.CompletedTask;
}
public ValueTask ServeFromCacheAsync(OutputCacheContext context, CancellationToken cancellation) => ValueTask.CompletedTask;
public ValueTask ServeResponseAsync(OutputCacheContext context, CancellationToken cancellation) => ValueTask.CompletedTask;
}
这是我想要缓存的 API:
[HttpPost("Filter")]
[OutputCache( PolicyName = "default" )]
public ActionResult<GenericResponse<IQueryable<CategoryEntity>>> Filter(CategoryFilterDto dto) => Result(_repository.Filter(dto));
这里的问题是,Api 将从客户端提供的 Body 参数中进行一些过滤,而我想根据客户端发送的参数进行更改。 我在互联网上搜索,看到了
VaryByParams
属性,但它似乎在 .NET 7 中不存在。
如何根据 .NET 7 的 OutputCache 中给定的主体参数改变输出
刚刚遇到了同样的问题,这就是我最终的做法:
builder.AddPolicy<CachingPolicy>().VaryByValue(
(context) => {
context.Request.EnableBuffering();
using var reader = new StreamReader(context.Request.Body, leaveOpen: true);
var body = reader.ReadToEndAsync();
// Reset the stream position to enable subsequent reads
context.Request.Body.Position = 0;
var keyVal = new KeyValuePair<string, string>("requestBody", body.Result);
return keyVal;
}
)
本质上,这将整个主体的字符串表示形式添加为构成缓存键的值之一。这可能并不理想,因为更改正文的任何内容,即使只是空白,都会导致非缓存响应,但它应该是完善实现的一个很好的起点。如果我最终自己改进它,我会编辑这个答案。