【发布时间】:2021-11-16 18:01:41
【问题描述】:
我需要根据查询字符串中的布尔值来决定是否缓存响应。不幸的是,我找不到这样的例子。你能帮帮我吗?
【问题讨论】:
标签: asp.net-core caching asp.net-core-mvc responsecache
我需要根据查询字符串中的布尔值来决定是否缓存响应。不幸的是,我找不到这样的例子。你能帮帮我吗?
【问题讨论】:
标签: asp.net-core caching asp.net-core-mvc responsecache
您可以为该场景创建一个自定义中间件,该中间件从查询中读取布尔值并根据该值缓存响应(无论可能是什么)。
您可以阅读自定义中间件here。
您的中间件应如下所示:
public class OptionalCachingMiddleware
{
private readonly RequestDelegate _next;
private readonly IServiceProvider _services;
public OptionalCachingMiddleware(RequestDelegate next, IServiceProvider services)
{
_next = next;
_services= services;
}
public async Task InvokeAsync(HttpContext context)
{
var shouldCache = bool.Parse(context.Request.Query["your-query-parameter-name"]);
if (shouldCache)
{
var responseCache = _services.GetRequiredService<IResponseCache>();
// put your caching logic here
}
// Call the next delegate/middleware in the pipeline
await _next(context);
}
}
【讨论】: