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

时间:2019-08-14 09:29:43

标签: c# asp.net-core caching .net-core asp.net-core-webapi

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

我碰到了几篇文章,提到如果请求包含Authorization标头将无法进行缓存,这让我有些惊讶。

Response caching conditions

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

1 个答案:

答案 0 :(得分:1)

对于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