如何允许需要 Authorization 标头的缓存 API 端点?

woo*_*ddy 6 c# caching .net-core asp.net-core asp.net-core-webapi

我正在寻找一种方法来缓存来自在 .NET Core 中开发的 API 端点的响应。作为要求的一部分,对 API 的请求必须具有有效的Authorization标头。

我看到几篇文章提到如果请求包含Authorization标头,缓存将是不可能的,这让我有点惊讶。

响应缓存条件

那么我应该如何解决这个问题呢?是否有任何库可以为这种场景启用缓存?

Tao*_*hou 6

对于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;
}
Run Code Online (Sandbox Code Playgroud)

并且,ResponseCachingPolicyProviderHeaderNames.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;
}
Run Code Online (Sandbox Code Playgroud)

对于ResponseCachingPolicyProvider,它是内部的,您无法从外部更改Microsoft.AspNetCore.ResponseCaching。不建议启用缓存Authorization,如果您坚持,可以ResponseCachingMiddleware参考ResponseCaching实现自己的缓存。