Search code examples
c#asp.net-mvc-4outputcachewebimage

MVC WebImage OutputCache results in content type of text/html


I'm trying to add an OutputCache to an MVC Action that has a WebImage.Write() response but as soon as I add it (even with a duration of 0) the content type changes from image/jpeg to text/html and I get the image rendered out as text in the browser.

sample code - this works correctly if the OutputCache attribute is removed:

[OutputCache(Duration = 3000)]
public void GetImage(Guid id)
{
    //Create WebImage from byte[] stored in DB
    DbImage image = DbImageDAL.SelectSingle(e => e.DbImageId == id);
    WebImage webimage = new WebImage(image.Data);

    webImage.Write();
    //Tried webImage.Write("JPEG"); but it makes not difference
}

Solution

  • OutputCache overrides the ContentType. You can fix this by deriving a class from OutputCacheAttribute like so:

    public class ImageOutputCache : OutputCacheAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            base.OnResultExecuting(filterContext);
            filterContext.HttpContext.Response.ContentType = "image/jpeg";
        }
    }