1

I have just implemented output caching of my Asp.Net Web API Controllers using StrathWeb's library connecting to the StackExchange.Redis library connecting through to an Azure-hosted Redis Cache.

I have written a custom class that implements the StrathWeb IApiOutputCache interface and calls the equivalent StackExchange methods. This is registered as the cache output provder in Global.asax.cs.

Here's an example of usage:

public class MyApiController : ApiController
{
  private const int FIFTEEN_MINUTES_IN_SECONDS = 900;

  [CacheOutput(ClientTimeSpan = FIFTEEN_MINUTES_IN_SECONDS, ServerTimeSpan = FIFTEEN_MINUTES_IN_SECONDS)]
  async public Task<Data> GetAsync(int param1, string param2)
  {
    return await GetExpensiveData();
  }

  [Serializable]
  public class Data
  {
    // Members omitted for brevity
  }
}

When a call is made to the api endpoint I can see that the framework correctly calls all the required methods on my IApiOutputCache class: Contains, Set and Get. However, even when a cached copy is found and returned, the GetExpensiveData() method is always run and the 'fresh' data returned.

No errors are thrown. The cache seems to be working. Yet, my expensive code is always called.

Thanks for your help :).

1
  • 3
    Can you share your IApiOutputCache Redis implementation? Commented Feb 1, 2015 at 15:50

1 Answer 1

2

Problem solved. I was incorrectly calling into Redis from my IApiOutputCache class.

Before...

public class AzureRedisApiOutputCache : IApiOutputCache
{
  public object Get(string key)
  {
    return AzureRedisCache.Instance.GetDatabase().StringGet(key);
  }
}

After...

public class AzureRedisApiOutputCache : IApiOutputCache
{
  public object Get(string key)
  {
    // Call the extension method that also performs deserialization...
    return AzureRedisCache.Instance.GetDatabase().Get(key);
  }
}

public static class RedisDatabaseExtensions
{
    public static object Get(this IDatabase cache, string key)
    {
        return Deserialize<object>(cache.StringGet(key));
    }
}

This confused me for some time as the CacheOutput framework never reported an error. It just silently failed and fell back to the controller method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.