I was looking at a way for caching responses from an API endpoint developed in .NET Core. The request to the API must have a valid Authorization
header as part the requirement.
I came across a few articles mentioning that caching wouldn't be possible if the request contains Authorization
header, which was a bit of surprise to me.
So how should I tackle this problem? Are there any libraries that can possibly enable caching for this kind of scenario?
Caching in REST APIs POST requests are not cacheable by default but can be made cacheable if either an Expires header or a Cache-Control header with a directive, to explicitly allows caching, is added to the response. Responses to PUT and DELETE requests are not cacheable at all.
The Cache API is a system for storing and retrieving network requests and their corresponding responses. These might be regular requests and responses created in the course of running your application, or they could be created solely for the purpose of storing data for later use.
You use caching when you have a highly concurrent need to read the same data, or for any application that has heavy read and write. You can also use caching for frequently accessed information. For example, caching is useful for COVID APIs.
For The Authorization header must not be present.
, this is by default.
For ResponseCachingMiddleware
which will call IResponseCachingPolicyProvider
to check whether to cache the reponse by if (_policyProvider.AllowCacheStorage(context))
like below:
// Should we store the response to this request?
if (_policyProvider.AllowCacheStorage(context))
{
// Hook up to listen to the response stream
ShimResponseStream(context);
try
{
await _next(httpContext);
// If there was no response body, check the response headers now. We can cache things like redirects.
await StartResponseAsync(context);
// Finalize the cache entry
await FinalizeCacheBodyAsync(context);
}
finally
{
UnshimResponseStream(context);
}
return;
}
And, ResponseCachingPolicyProvider will check HeaderNames.Authorization
by
public virtual bool AttemptResponseCaching(ResponseCachingContext context)
{
var request = context.HttpContext.Request;
// Verify the method
if (!HttpMethods.IsGet(request.Method) && !HttpMethods.IsHead(request.Method))
{
context.Logger.RequestMethodNotCacheable(request.Method);
return false;
}
// Verify existence of authorization headers
if (!StringValues.IsNullOrEmpty(request.Headers[HeaderNames.Authorization]))
{
context.Logger.RequestWithAuthorizationNotCacheable();
return false;
}
return true;
}
For ResponseCachingPolicyProvider, it is internal which you could not change from outside Microsoft.AspNetCore.ResponseCaching
. It is not recommended to enable cache for Authorization
, if you insist on, you could implement your own ResponseCachingMiddleware
by refer ResponseCaching.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With