微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何缓存输出的action方法,返回图像到asp.net mvc中的视图?

我已经阅读了很多关于缓存的帖子,但是没有一个真正符合我的需求.在我的mvc 3应用程序中,我有一个Get Image()方法返回一个图像类型的文件.然后我在这个视图中使用这种方法显示图像:
<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)

2)在Getimage()方法中使用以下Response.Cache方法

public FileContentResult Getimage(int productId)
    {
        Response.Cache.SetCacheability(HttpCacheability.Public);
        Response.Cache.SetMaxAge(new TimeSpan(0,10));
        Response.Cache.SetExpires(DateTime.Now.Add(new TimeSpan(0,10)));
        Response.Cache.AppendCacheExtension("must-revalidate,proxy-revalidate");        
        // other code is the same
    }

图像不缓存

3)这里我得到:304未修改,但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,Location = OutputCacheLocation.ServerAndClient)]
public ActionResult Getimage(string productId)
{
    ...
}

注意事项:使用OutputCacheLocation.ServerAndClient并取消NoStore = true.

原文地址:https://www.jb51.cc/aspnet/246388.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐