我正在尝试缓存对 webapi 端点请求的响应。
我创建了一个 DelegatingHadler,它使用先前生成的响应使管道短路,但它不起作用。
我究竟做错了什么?或者我怎样才能正确地做到这一点?
这是我的DH:
public class StuffCache : DelegatingHandler
{
public const string URL_CACHED = @"/stuff-endpoint/items";
ObjectCache cache = MemoryCache.Default;
public StuffCache()
{
cache = MemoryCache.Default;
}
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Get)
{
if (request.RequestUri.AbsolutePath.ToLower() == URL_CACHED)
{
HttpResponseMessage response = (HttpResponseMessage)cache["CachedItemName"];
if (response == null)
{
response = await base.SendAsync(request, cancellationToken);
cache.Add("CachedItemName", response, null);
}
return response;
}
}
return await base.SendAsync(request, cancellationToken);
}
}