代码之家  ›  专栏  ›  技术社区  ›  Hadi Eskandari

ASP。NET MVC图像参数缓存

  •  1
  • Hadi Eskandari  · 技术社区  · 17 年前

    因此,无论参数值如何,通过调用操作返回的图像总是相同的。有办法解决这个问题吗?

    
    public class ImageResult : ActionResult  
    {  
        public Image Image  
        {  
            get; set;  
        }  
    
        public ImageFormat ImageFormat  
        {  
            get; set;  
        }  
    
        private static Dictionary FormatMap  
        {  
            get; set;  
        }  
    
        static ImageResult()  
        {  
            CreateContentTypeMap();  
        }  
    
        public override void ExecuteResult(ControllerContext context)  
        {  
            if (Image == null) throw new ArgumentNullException("Image");  
            if (ImageFormat == null) throw new ArgumentNullException("ImageFormat");  
    
            context.HttpContext.Response.Clear();  
            context.HttpContext.Response.ContentType = FormatMap[ImageFormat];  
    
            Image.Save(context.HttpContext.Response.OutputStream, ImageFormat);  
        }  
    
        private static void CreateContentTypeMap()  
        {  
            FormatMap = new Dictionary  
            {  
                { ImageFormat.Bmp,  "image/bmp"                },  
                { ImageFormat.Gif,  "image/gif"                },  
                { ImageFormat.Icon, "image/vnd.microsoft.icon" },  
                { ImageFormat.Jpeg, "image/Jpeg"               },  
                { ImageFormat.Png,  "image/png"                },  
                { ImageFormat.Tiff, "image/tiff"               },  
                { ImageFormat.Wmf,  "image/wmf"                }  
            };  
        }  
    }  
    
    

    以及控制器动作:

    
    public ActionResult GetCalendarBadge(DateTime displayDate)
    {
        var bmp = SomeBitmap();
        var g = Graphics.FromImage(bmp);
    
        //GDI+ to draw the image.
    
        return new ImageResult { Image = bmp, ImageFormat = ImageFormat.Png };
    }
    
    

    
    <% foreach(var item in this.Model.News) { %>  
          <%= Html.Image<NewsController>(o => o.GetCalendarBadge(item.DisplayDate), 75, 75)%>
    <% } %>
    
    

    
      context.HttpContext.Response.Cache.SetNoStore();  
      context.HttpContext.Response.Expires = 0;  
      context.HttpContext.Response.AppendHeader("Pragma", "no-cache");  
    
    
    2 回复  |  直到 13 年前
        1
  •  0
  •   Iain Holder    17 年前

    我认为这种行为是通过动作上的缓存属性“选择加入”的。

        2
  •  0
  •   Hadi Eskandari    17 年前

    发现问题了!这是由于使用Windsor IoC并将控制器注册/解析为Singleton(这是默认行为)。将生活方式改为瞬态解决了这个问题(以及其他问题)。

    here