I'm trying to cache a response to a webapi endpoint requests.
I've created a DelegatingHadler that short circuits the pipeline reusing a previously generated response, and it does not work.
What am I doing wrong? or how can I do it correctly?
This is my 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);
}
}