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:
我已经阅读了很多关于缓存的帖子,但其中没有一篇确实符合我的需求。在我的mvc 3应用程序中,我有一个动作方法GetImage(),它返回一个图像类型的文件。然后我在视图中使用此方法来显示图像:
<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) to use OutputCacheAttribute:
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");
}
Images are not cached (I get status: 200 OK)
图像没有缓存(我得到状态:200 OK)
2) to use the following Response.Cache methods in a GetImage() method:
2)在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
}
Images are not cached
图像未缓存
3) Here I get: 304 Not Modified, but the GetImage() method returns nothing (empty image)
3)我得到: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
}
Question: How to cache the output of this action method on a server?
问题:如何在服务器上缓存此操作方法的输出?
13
Try like this:
试试这样:
[HttpGet]
[OutputCache(
Duration = 10,
VaryByParam = "productId",
Location = OutputCacheLocation.ServerAndClient)]
public ActionResult GetImage(string productId)
{
...
}
Things to notice: using OutputCacheLocation.ServerAndClient
and gotten rid of NoStore = true
.
需要注意的事项:使用OutputCacheLocation.ServerAndClient并摆脱NoStore = true。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2013/02/08/e777cd3343cc8ebe036ba3aadfa8da41.html。