如何允许需要Authorization标头的Caching API端点? [英] How to allow Caching API endpoint that requires Authorization header?

查看:52
本文介绍了如何允许需要Authorization标头的Caching API端点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was looking at a way for caching responses from an API endpoint developed in .NET Core. The request to the API must have a valid Authorization header as part the requirement.

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

I came across a few articles mentioning that caching wouldn't be possible if the request contains Authorization header, which was a bit of surprise to me.

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

So how should I tackle this problem? Are there any libraries that can possibly enable caching for this kind of scenario?

推荐答案

对于必须不存在Authorization标头.,默认情况下.

对于 ResponseCachingMiddleware ,它将调用 IResponseCachingPolicyProvider 来检查是否通过 if(_policyProvider.AllowCacheStorage(context))来缓存响应,如下所示:

For ResponseCachingMiddleware which will call IResponseCachingPolicyProvider to check whether to cache the reponse by if (_policyProvider.AllowCacheStorage(context)) like below:

// 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;
}

而且

And, ResponseCachingPolicyProvider will check HeaderNames.Authorization by

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;
}

对于ResponseCachingMiddleware aspnet/AspNetCore/tree/cc1f23c5f8afb7d2a00405f19811d2372c4fcec2/src/Middleware/ResponseCaching"rel =" nofollow noreferrer> ResponseCaching .

For ResponseCachingPolicyProvider, it is internal which you could not change from outside Microsoft.AspNetCore.ResponseCaching. It is not recommended to enable cache for Authorization, if you insist on, you could implement your own ResponseCachingMiddleware by refer ResponseCaching.

这篇关于如何允许需要Authorization标头的Caching API端点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆