【问题标题】:Outputcache 1 action, 2 views输出缓存 1 个动作,2 个视图
【发布时间】:2016-03-30 11:39:46
【问题描述】:

所以我有以下操作,我正在尝试将输出缓存添加到:

[OutputCache(CacheProfile = OutputCacheProfileNames.Hours24)]
public ActionResult ContactUs()
{
  ContactUsModel model = _modelBuilder.BuildContactUsModel();

  if (Request.IsAjaxRequest())
  {
    return Json(StringFromPartial(partialTemplate, model), JsonRequestBehavior.AllowGet);
  }
  else
  {
    return View(model);
  }
}

但这似乎缓存了请求的第一个视图 - 即 json OR 普通视图。

有没有办法让输出缓存对两个视图都起作用,而不必将它们从同一个操作中拆分出来?

【问题讨论】:

  • 尝试 [OutputCache(Duration = 10, VaryByParam = "name")]
  • @REDEVI_ 不幸的是我不能使用VaryByParam,因为没有将参数传递给操作,我会阅读那个自定义的东西,但看起来它可能是要走的路

标签: asp.net-mvc outputcache


【解决方案1】:

您在回答您自己的问题时击败了我,但我认为这段代码可能仍然有用。由于用户不同是一种常见的情况,您可能应该考虑到能够做到这一点并且您的 AJAX 会有所不同。此代码将允许您通过附加到单个字符串来改变任意数量的自定义参数。

public override string GetVaryByCustomString(System.Web.HttpContext context, string custom)
{
    var args = custom.ToLower().Split(';');
    var sb = new StringBuilder();

    foreach (var arg in args)
    {
        switch (arg)
        {
            case "user":
                sb.Append(User.Identity.Name);
                break;
            case "ajax":
                if (context.Request.Headers["X-Requested-With"] != null)
                {
                    // "XMLHttpRequest" will be appended if it's an AJAX request
                    sb.Append(context.Request.Headers["X-Requested-With"]);
                }
                break;
            default:
                continue;
        }
    }

    return sb.ToString();
}

然后,如果您需要更改多个自定义参数,您只需执行以下操作。

[OutputCache(CacheProfile = OutputCacheProfileNames.Hours24, VaryByCustom = "User;Ajax")]

然后,如果您需要额外的自定义变量参数,您只需不断添加 case 语句来涵盖这些场景。

【讨论】:

  • 不错,没想到多场景案例
【解决方案2】:

感谢 REDEVI_ 的 cmets 为我指明了正确的方向,我已经能够解决这个问题。

我将输出缓存更改为:

[OutputCache(CacheProfile = OutputCacheProfileNames.Hours24, VaryByCustom = "IsAjax")]

然后在我的 global.asax 文件中,我添加了以下覆盖:

    public override string GetVaryByCustomString(HttpContext context, string custom)
    {
        if (context != null)
        {
            switch (custom)
            {
                case "IsAjax":
                    return new HttpRequestWrapper(context.Request).IsAjaxRequest() ? "IsAjax" : "IsNotAjax";
            }
        }

        return base.GetVaryByCustomString(context, custom);
    }

【讨论】:

    猜你喜欢
    • 2011-01-13
    • 2019-04-17
    • 2013-10-13
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 2011-01-15
    相关资源
    最近更新 更多