filipw / Strathweb.CacheOutput

ASP.NET Web API CacheOutput - library to allow you to cache the output of ApiControllers
Other
882 stars 253 forks source link

Avoid caching MediaTypeHeaderValue that is not serializable #165

Open micdenny opened 8 years ago

micdenny commented 8 years ago

In general every class that is not a POCO class should not be cached, otherwise it becomes difficult to implement a caching provider based on a distributed caching system.

I'm developing an extension for AppFabric (the same will be when I will implement the Redis extension), and I'm blocked because CacheOutputAttribute tries to put in cache a .net framework object MediaTypeHeaderValue that is not serializable.

If caching that whole object is necessary we should think to use a POCO class instead, that share the same structure:

public class MyMediaTypeHeaderValue
{
        public string CharSet { get; set; }
        public string MediaType { get; set; }
        public List<NameValueHeaderValue> Parameters { get; set; }
}
micdenny commented 8 years ago

I saw now that should be enough to cache this responseContent.Headers.ContentType.ToString() and simply use the MediaTypeHeaderValue.TryParse:

            MediaTypeHeaderValue contenttype = null;
            var ct = _webApiCache.Get<string>(cachekey + Constants.ContentTypeKey);
            if (ct != null)
            {
                if (!MediaTypeHeaderValue.TryParse(ct, out contenttype))
                {
                    contenttype = new MediaTypeHeaderValue(cachekey.Split(new[] { ':' }, 2)[1].Split(';')[0]);
                }
            }

and

var contentType = responseContent.Headers.ContentType.ToString();
                        _webApiCache.Add(cachekey + Constants.ContentTypeKey,
                                        contentType,
                                        cacheTime.AbsoluteExpiration, baseKey);
micdenny commented 8 years ago

I've submitted a PR to fix this

micdenny commented 8 years ago

I need that PR to be merged or discussed to have a working implementation of AppFabric provider: https://github.com/micdenny/Strathweb.CacheOutput.WebApi2.AppFabric

felickz commented 8 years ago

+1 writing a redis provider, same root issue.

Iamcerba commented 7 years ago

This happened because MediaTypeHeaderValue has read only properties and depending on your Lib which is serializing, for example JSON.NET, custom JsonConverter is needed.

TedCrocker commented 5 years ago

I have run into this issue as well trying to implement a FileCache option, any eta?