【问题标题】:OutputCache not working when using Reponse.Cookies使用 Reponse.Cookies 时,OutputCache 不起作用
【发布时间】:2013-07-30 12:05:23
【问题描述】:

我正在尝试缓存 ActionResult。在特定的 ActionResult 中,我正在向 cookie 写入一些数据。输出缓存在该操作结果中不起作用。它适用于我不使用 Response.Cookies 的所有其他操作。请帮我解决这个问题。

我正在使用 ASP.NET MVC 4


编辑

(包括代码)

 [OutputCache(Duration = 8000, VaryByParam = "*")]
    public ActionResult List(SearchViewModel searchViewModel, int page = 1, int mode = 1)
    {
        HttpCookie ck = Request.Cookies["Geo"];
        string lat = string.IsNullOrEmpty(Request.Params["lat"]) ? null : Request.Params["lat"];
        string lng = string.IsNullOrEmpty(Request.Params["lng"]) ? null : Request.Params["lng"];
        if (ck == null)
        {
            ck = new HttpCookie("Geo");
            Response.Cookies.Add(ck);
        }
        if (lat != null)
        {
            ck["Lat"] = lat;
            ck["Lon"] = lng;
            ck.Expires = DateTime.Now.AddMonths(2);
            Response.Cookies.Set(ck);
//this is the code which causes problem. If I remove this section catching will work
//other logic goes here.. 
        }
     }

【问题讨论】:

  • 您能发布到目前为止您尝试过的内容吗?没有代码,我们无法看到您做错了什么并提供帮助。
  • 我已经更新并包含了代码
  • 我遇到了同样的问题,当在操作中写入 cookie 时 outputcache 将无法工作

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


【解决方案1】:

请参考微软文档: https://msdn.microsoft.com/en-us/library/system.web.httpcookie.shareable(v=vs.110).aspx

如果给定的 HttpResponse 包含一个或多个出站 cookie,并且 Shareable 设置为 false(默认值),则响应的输出缓存将被抑制。这可以防止包含潜在敏感信息的 cookie 缓存在响应中并发送到多个客户端。

要允许缓存包含 cookie 的响应,请配置缓存 通常用于响应,例如使用 OutputCache 指令或 MVC 的 [OutputCache] 属性,并将所有出站 cookie 设置为 将 Shareable 设置为 true。

所以基本上,请确保您已将所有 cookie 设置为:

cookie.Shareable = true; // Needed with Outputcache

【讨论】:

    【解决方案2】:

    我在this other question找到了答案。

    看起来OutputCache 缓存了请求的输出,因此对于具有相同参数的相同请求,它不会运行 action 方法中的代码,它只会返回相同的输出。因此,您的任何代码都不会在后续请求中运行。

    看起来其他帖子中的答案有一些可能的解决方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 2014-09-04
      相关资源
      最近更新 更多