I have requirement to read a pretty much static JSON file on every request. I'm using ASP.NET web API 2 targetting .NET 4.5. I had inteded to use the System.Runtime.Caching.Memory cache for the same. I'm using this Caching in the Delegating message Handler. To my surprise the cache is not working at all. Every time the request is coming, the cache key does not seem to exist and it just keeps loding the file. To test the same I was using IIS Express 8.0 and used break point n VS 2012.
My code is as below
public class AuthenticationHandler:DelegatingHandler
{
ObjectCache currentCache = MemoryCache.Default;
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
if (!request.Headers.Contains("source"))
request.Headers.Add("source", "1");
var exclusionList = GetFromCache();
if (exclusionList.Exists(item => request.RequestUri.OriginalString.ToLower().Contains(item.ToLower())))
{
return base.SendAsync(request, cancellationToken);
}
else if (request.Headers.Contains("id"))
{
return base.SendAsync(request, cancellationToken);
}
else
{
TaskCompletionSource<HttpResponseMessage> responseMessageTask = new TaskCompletionSource<HttpResponseMessage>();
HttpResponseMessage response = request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, "Session id not present in the header");
responseMessageTask.SetResult(response);
return responseMessageTask.Task;
}
}
private List<string> GetFromCache()
{
//ObjectCache currentCache = MemoryCache.Default;
//var currentCache = HttpContext.Current.Cache;
CacheItemPolicy expirationPolicy = new CacheItemPolicy();
var exclusionList = currentCache.Get("__ExclusionList") as List<string>;
if (exclusionList == null)
{
string filePath = HostingEnvironment.MapPath("~/config/Exclusion.config");
string jsonConfig = File.ReadAllText(filePath);
exclusionList = JsonConvert.DeserializeObject<List<string>>(jsonConfig);
CacheItem item = new CacheItem("__ExclusionList");
item.Value = exclusionList;
expirationPolicy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string>() { filePath }));
}
return exclusionList;
}
}
In the GetFromCache function, when I put the break point in if segment, I see that the content is always loaded from the file and not from cache at any instance. Can you please tell me if I'm missing something?