我正在寻找一种缓存来自 .NET Core 中开发的 API 端点的响应的方法。作为要求的一部分,对 API 的请求必须具有有效的
Authorization
标头。
我看到一些文章提到,如果请求包含
Authorization
标头,则无法进行缓存,这让我有点惊讶。
那么我该如何解决这个问题呢?是否有任何库可以为这种情况启用缓存?
对于
The Authorization header must not be present.
,这是默认设置。
对于
ResponseCachingMiddleware
,它将调用IResponseCachingPolicyProvider
来检查是否通过if (_policyProvider.AllowCacheStorage(context))
缓存响应,如下所示:
// 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;
}
并且, ResponseCachingPolicyProvider 将通过
检查
HeaderNames.Authorization
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;
}
对于 ResponseCachingPolicyProvider,它是内部的,您无法从外部更改
Microsoft.AspNetCore.ResponseCaching
。 不建议为Authorization
启用缓存,如果你坚持的话,你可以参考ResponseCaching实现你自己的
ResponseCachingMiddleware
。