Strathweb CacheOutputAttribute 不会在 http 响应或其他地方添加一些可靠信息,以允许知道响应是否来自缓存。
您可以从中派生出这样做,然后将您对 CacheOutputAttribute 的所有用法替换为您自己的。
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class YourCustomizedCacheOutputAttribute : CacheOutputAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
// If response is set, it has been retrieved from cache.
actionContext.Request.Properties["yourCacheHitKey"] =
actionContext.Response != null;
}
}
当然,如果您无法访问它,请使用 HttpRequestMessage.Properties 以外的其他内容。
您可以通过示例添加一些自定义标头作为响应,如果将其泄露给浏览器对您来说不是问题:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class YourCustomizedCacheOutputAttribute : CacheOutputAttribute
{
// "X-" prefix is deprecated, but the rational behind this is about wannabe
// standard header. I do not intend this one to become standard for anything.
private const string _cacheHeader = "X-Cache";
protected override void ApplyCacheHeaders(HttpResponseMessage response,
CacheTime cacheTime)
{
base.ApplyCacheHeaders(response, cacheTime);
if (response.Headers.Contains(_cacheHeader))
return;
// At this point, we do not know. miss by default.
response.Headers.Add(_cacheHeader, "miss");
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
if (actionContext.Response == null)
return;
// Response has been retrieved from cache.
// Headers.Remove does not fail if not already there.
response.Headers.Remove(_cacheHeader);
actionContext.Response.Headers.Add(_cacheHeader, "hit");
}
}