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

问题描述 投票:0回答:2

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

Authorization
标头。

我看到一些文章提到,如果请求包含

Authorization
标头,则无法进行缓存,这让我有点惊讶。

Response caching conditions

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

c# asp.net-core caching .net-core asp.net-core-webapi
2个回答
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;
}

并且, 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


0
投票

首先,您必须确定是否需要服务器端缓存或客户端缓存,或两者都需要。如果您只需要客户端缓存,则只需将

cache-control
标头添加到响应中即可。
如果您需要服务器端缓存,那么您将需要 ResponseCache 或 OutputCache 中间件。

我在这里写了关于客户端缓存和更广泛问题的博客文章。

如果您需要服务器缓存,那么有一个存储库here,它是 AspNet Core ResponseCache 中间件的默认版本,但添加了

AllowAuthorizedEndpoint
标志。

© www.soinside.com 2019 - 2024. All rights reserved.