I need to decide whether to cache the response according to the boolean value from the query string. Unfortunately, I couldn't find such an example. Can you help me?
Asked
Active
Viewed 293 times
1 Answers
0
You can create a custom middleware for that scenario, which reads the boolean value from the query and caches the response (whatever that may be) according to that value.
You can read about custom middlewares here.
Your middleware should look something like this:
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);
}
}

fbede
- 843
- 9
- 12
-
So how can I use the response cache here? In Memory Cache is ok, but I couldn't come up with an idea for the response cache. – Blackerback Nov 15 '21 at 15:01
-
You can inject an IResponseCache service into you middleware and use that. – fbede Nov 15 '21 at 15:06
-
Thank you i will investigate – Blackerback Nov 15 '21 at 15:25