如何缓存返回图像在asp.net mvc的视图操作方法的输出? [英] How to cache output of action method that returns image to the view in asp.net mvc?
问题描述
我读过很多有关缓存的职位了,但没有人其实完全匹配我的需求。在我的MVC 3应用程序我有一个动作方法的getImage()返回图像类型的文件。然后,我用这个方法在一个视图中显示图片:
I've read lots of posts about caching already, but none of them actually match my needs exactly. In my mvc 3 app I have an action method GetImage() that returns a File of image type. Then I use this method in a view to display image:
<img width="75" height="75" src="@Url.Action("GetImage", "Store", new {productId = item.ProductId})"/>
我想在服务器上缓存图像。所以,我已经尝试过:
I want to cache images on a Server. So, what I've already tried:
1)使用OutputCacheAttribute:
1) to use 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)
Images are not cached (I get status: 200 OK)
2)使用以下Response.Cache方法中的getImage()方法
2) to use the following Response.Cache methods in a GetImage() method:
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
}
图像不缓存
3)在这里,我得到:304未修改,但的getImage()方法返回什么(空图片)
3) Here I get: 304 Not Modified, but the GetImage() method returns nothing (empty image)
public FileContentResult GetImage(int productId)
{
Response.StatusCode = 304;
Response.StatusDescription = "Not Modified";
Response.AddHeader("Content-Length", "0");
// other code is the same
}
问:怎样缓存此操作方法的输出在服务器上
Question: How to cache the output of this action method on a server?
推荐答案
尝试这样的:
[HttpGet]
[OutputCache(
Duration = 10,
VaryByParam = "productId",
Location = OutputCacheLocation.ServerAndClient)]
public ActionResult GetImage(string productId)
{
...
}
事情需要注意:使用 OutputCacheLocation.ServerAndClient
和摆脱了 NoStore = TRUE
这篇关于如何缓存返回图像在asp.net mvc的视图操作方法的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!