【问题标题】:MVC WebImage OutputCache results in content type of text/htmlMVC WebImage OutputCache 导致内容类型为 text/html
【发布时间】:2023-03-28 07:20:02
【问题描述】:

我正在尝试将 OutputCache 添加到具有 WebImage.Write() 响应的 MVC 操作,但只要我添加它(即使持续时间为 0),内容类型就会从 image/jpeg 更改为 text/ html,然后我将图像呈现为浏览器中的文本。

示例代码 - 如果 OutputCache 属性被删除,这将正常工作:

[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
}

【问题讨论】:

    标签: c# asp.net-mvc-4 outputcache webimage


    【解决方案1】:

    OutputCache 覆盖 ContentType。您可以通过从 OutputCacheAttribute 派生一个类来解决此问题,如下所示:

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

    【讨论】:

    • 感谢@Pete,这太完美了!
    • 对于更通用的版本,您可以在调用 base.OnResultExecuting 之前存储 ContentType 的当前值,然后在最后将其设置回来。
    猜你喜欢
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 2014-03-11
    • 2012-03-28
    相关资源
    最近更新 更多