我正在寻找一种方法来缓存来自在 .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
启用缓存,如果你坚持,你可以自己实现ResponseCachingMiddleware
引用 ResponseCaching .
关于c# - 如何允许需要 Authorization header 的缓存 API 端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57491941/