c# - 如何允许需要 Authorization header 的缓存 API 端点?

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

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

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

Response caching conditions

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

最佳答案

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

相关文章:

c# - 为什么 String.IsBOMWhitespace() 方法总是返回 false?

asp.net - 当前上下文中不存在名称 "Configuration"

c# - 生成 Swagger.json 文件后如何以编程方式访问它

ruby-on-rails - 使用类变量缓存(大型和静态)数据

c# - 在 SQL Server 2005 中加载 CRL 程序集 : The given assembly name or codebase was invalid.(HRESULT 异常:0x80131047)

c# - 通过 API Microsoft Bot Framework 返回货币汇率

c# - 如何在 Razor MVC asp.net 中组合两个 View 模型

c# - 带有 SSL 证书的 .Net Core 连接服务

Spring Redis缓存不驱逐

java - CacheBuilder.newBuilder().build 不明确