3

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
}
Rob
  • 10,004
  • 5
  • 61
  • 91

1 Answers1

6

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";
    }
}
Pete
  • 6,585
  • 5
  • 43
  • 69
  • For a more generic version, you can store the current value of ContentType before the call to base.OnResultExecuting and then set it back at the end. – Mog0 Jan 25 '16 at 13:57