0

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?

1 Answers1

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