【问题标题】:How to manually run method with OutputCacheAttribute如何使用 OutputCacheAttribute 手动运行方法
【发布时间】:2014-11-30 13:55:11
【问题描述】:

我有方法:

    [HttpGet]
    [OutputCache(Duration = 300, Location = OutputCacheLocation.Client)]     
    public JsonResult TopNotification(Guid? portalIdentifier, string url)
    {
        var notificationMessages = new List<NotificationModel>();

        //Filling notification messages

        return Json(notificationMessages, JsonRequestBehavior.AllowGet);
    }

从基础布局调用:@Html.Partial("TopNotification")

如果在缓存持续时间结束之前发生某些操作,我需要重写我的 notificationMessages。 当用户访问某个 URL 时,我需要重新填写消息。

【问题讨论】:

标签: c# asp.net-mvc-4 outputcache


【解决方案1】:

如果您在服务器端移动缓存,那么您可以使用 OutputCache 的 VaryByParam 属性来存储缓存版本信息。然后在 Global.asax 中覆盖 GetVaryByCustomString 并返回当前版本的缓存。

每次访问reset URL时,都可以提高缓存的版本,从而使输出缓存失效。

例子:

[OutputCache(Duration = 300, Location = OutputCacheLocation.Server, VaryByCustom = "cache")]
public JsonResult TopNotification(Guid? portalIdentifier, string url) {...}

在 Global.asax 中:

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if (custom.Equals("cache"))
        return Cache.Version; // something like that

    return base.GetVaryByCustomString(context, custom);
}

当访问重置 URL 时,提高缓存的版本。所有后续的 TopNotification 调用都将获取新数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 2021-08-31
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多