MVC WebImage OutputCache results in content type of text/html
Asked Answered
T

1

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
}
Trug answered 13/6, 2013 at 13:58 Comment(0)
B
7

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";
    }
}
Burlington answered 13/6, 2013 at 14:17 Comment(1)
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.Reflexive

© 2022 - 2024 — McMap. All rights reserved.