【问题标题】:Conditional Output Caching in MVCMVC 中的条件输出缓存
【发布时间】:2013-05-27 20:50:37
【问题描述】:

我有一个 MVC 应用程序,我想为其缓存一个 Action 的输出,但有条件地基于业务逻辑。但是我运气不好,我知道 CacheOutputAttribute,但它是一个静态规则。

具体来说,我有一个文档表,用于存储 Intranet 站点的二进制数据。当提供的文档类型是图像时,我希望允许浏览器缓存文件,这样它就不需要每次都请求它。

我尝试了以下方法,但没有让浏览器将资产识别为可缓存。

public ActionResult View(Guid id)
{
    /*
        get document from database
    */
    switch (document.ContentType)
    {
        case "image/jpeg":
        case "image/tiff":
        case "image/x-png":
        case "image/png":
        case "image/gif":
            Response.Cache.SetExpires(DateTime.Now.AddMinutes(30));
            Response.Cache.SetCacheability(HttpCacheability.Private);
            Response.Cache.SetValidUntilExpires(true); 
            break;
    }
    return File(document.Data, document.ContentType);
}

【问题讨论】:

    标签: asp.net-mvc caching asp.net-mvc-4 outputcache


    【解决方案1】:

    【讨论】:

    • 或者您可以使用 VaryByCustom 属性。你可以在这里找到用法dhuvelle.com/2011/09/aspnet-mvc-custom-outputcache-with.html
    • VaryByParam 假设我的标准是请求的参数,但在这种情况下不是。我的逻辑取决于我使用 documentId 参数从数据库中获取的文档类型。 VaryByCustom 很接近,但它取决于您放置在 global.asax 中的单个函数(基于您链接的内容)。虽然我可以使用它来破解一些东西,但似乎如果我添加第二个具有条件缓存的页面,我会很高兴尝试在 global.asax 中维护该功能。
    猜你喜欢
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 2010-09-27
    相关资源
    最近更新 更多