Asp.net

如何記憶體將圖像返回到asp.net mvc中的視圖的操作方法的輸出?

  • January 9, 2015

我已經閱讀了很多關於記憶體的文章,但沒有一個真正符合我的需求。在我的 mvc 3 應用程序中,我有一個返回圖像類型文件的操作方法 GetImage()。然後我在視圖中使用這個方法來顯示圖像:

<img width="75" height="75" src="@Url.Action("GetImage", "Store", new {productId = item.ProductId})"/>

我想在伺服器上記憶體圖像。所以,我已經嘗試過:

1)使用OutputCacheAttribute:

   [HttpGet, OutputCache(Duration = 10, VaryByParam = "productId", Location = OutputCacheLocation.Server, NoStore = true)]
   public FileContentResult GetImage(int productId)
   {
       var p = _productRepository.GetProduct(productId);
       if (p != null)
       {
           if (System.IO.File.Exists(GetFullProductImagePath(productId)))
           {
               var image = Image.FromFile(GetFullProductImagePath(productId));
               return File(GetFileContents(image), "image/jpeg");
           }
       }
       var defaultPath = AppDomain.CurrentDomain.BaseDirectory +
                            ConfigurationManager.AppSettings["default-images-directory"];

       var defaultImage = Image.FromFile(Path.Combine(defaultPath, "DefaultProductImage.jpg"));
       return File(GetFileContents(defaultImage), "image/jpeg");
   }

圖像未記憶體(我得到狀態:200 OK)

  1. 在 GetImage() 方法中使用以下 Response.Cache 方法:
   public FileContentResult GetImage(int productId)
   {
       Response.Cache.SetCacheability(HttpCacheability.Public);
       Response.Cache.SetMaxAge(new TimeSpan(0, 0, 0, 10));
       Response.Cache.SetExpires(DateTime.Now.Add(new TimeSpan(0, 0, 0, 10)));
       Response.Cache.AppendCacheExtension("must-revalidate, proxy-revalidate");        
       // other code is the same
   }

圖像未記憶體

  1. 在這裡我得到:304 Not Modified,但 GetImage() 方法不返回任何內容(空圖像)
   public FileContentResult GetImage(int productId)
   {
       Response.StatusCode = 304;
       Response.StatusDescription = "Not Modified";
       Response.AddHeader("Content-Length", "0");     
       // other code is the same
   }

問題:如何在伺服器上記憶體此操作方法的輸出?

試試這樣:

[HttpGet]
[OutputCache(
   Duration = 10, 
   VaryByParam = "productId", 
   Location = OutputCacheLocation.ServerAndClient)]
public ActionResult GetImage(string productId)
{
   ...
}

注意事項:使用OutputCacheLocation.ServerAndClient和擺脫NoStore = true.

引用自:https://stackoverflow.com/questions/14769404