【问题标题】:Server Cache bug with OutputCache Attribute?OutputCache 属性的服务器缓存错误?
【发布时间】:2011-12-10 17:10:24
【问题描述】:

我是 MVC 初学者,今天遇到了一个奇怪的问题:我想使用 OutputCache 来启用一个 action 的缓存。代码如下:

 [OutputCache(Duration=86400,VaryByParam="none")]
    public ActionResult Index(string id)
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        ViewBag.ID = id;

        return View();
    }

注意“VaryByParam”属性是“none”,是的,我希望服务器只为操作保留一个缓存,无论传递的参数是什么。 路由代码是这样的:

 public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

然后我打开探索,结果不是我想要的,例如我输入:“http://localhost:27654/home/index/121212”,页面出来并显示id“121212”。但是当我更改为“http://localhost:27654/home/index/12”时,我看到页面已更改,显示 id“12”。

但是如果我刷新页面(参数“id”没有改变),页面中显示的日期时间没有改变,这意味着asp.net已经通过“ID”参数保持缓存变化,而不是我的设置。 怎么了?

【问题讨论】:

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


【解决方案1】:

是的。这是因为您通过路由中预定义的参数创建了另一个页面示例。

[OutputCache(Duration=86400,VaryByParam="none")]
    public ActionResult Index(int id, string some)
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        ViewBag.ID = id;
        ViewBag.Some = some;
        return View();
    }

路由参数不能作为 OutputCache 的参数。在我的例子中string some不是路由的一部分,所以如果你尝试这个例子,如果你可以使用参数some,新版本的缓存将不会被创建

另请阅读此主题:OutputCache Bug with VaryByParam="None" with MVC RC refresh

【讨论】:

  • 谢谢,这是否意味着在“Http Get”场景中,我不能使用路由参数,我必须使用 queryString 来传递参数?在你的示例中,我必须输入“localhost:27654/home/index?some=wawa
  • 这意味着如果在 routes.MapRoute 中定义的任何参数将发生变化 - 将创建新的缓存示例。 /home/index/1 或 /2 是路由参数,所以它将是 2 个缓存项。 QueryString 参数不会对缓存页面产生任何影响,导致 VaryByParam="none"。有道理吗?
猜你喜欢
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 2012-05-01
  • 2020-10-14
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
  • 2015-02-28
相关资源
最近更新 更多