使用OutputCache和GetVaryByCustomString为多个路径缓存相同的内容

时间:2017-07-11 05:35:14

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

我的MVC控制器中有以下代码:

[HttpGet]
[OutputCache(Duration = 3600, VaryByParam = "none", VaryByCustom = "app")]
public async Task<ViewResult> Index(string r)
{
   // Stuff...
}

我在Global.asax.cs类中有以下GetVaryByCustomString实现:

public override string GetVaryByCustomString(HttpContext context, string arg)
{
        switch (arg.ToLower())
        {
            case "app":
                return context.Request.Url.Host;

            default:
                return base.GetVaryByCustomString(context, arg);
        }
    }

在我们的应用程序中,客户将拥有自己的子域(即 johndoe.app.com janedoe.app.com )。

因此,子域名的缓存应该有所不同。

然而,任何&#34;路径&#34;在该完全限定的URL上应该共享相同的缓存。因此,以下内容应该读取相同的输出缓存:

  • johndoe.app.com /
  • johndoe.app.com/123
  • johndoe.app.com/abc

这是一个令人筋疲力尽的原因,为什么会这样,但简而言之,它是一个SPA应用程序,以及&#34;路径&#34;真的只是一个跟踪器。这不能更改为查询字符串。

当路径(跟踪器)更改时,将新访问索引方法。我可以通过调试器告诉我。作为注释,仍然会调用GetVaryByCustomString,但在处理完Index方法后调用它。

如何根据子域更改缓存,但是无论URL上的路径(跟踪器)如何,都使用该缓存?

如果它提供任何有益的东西,这就是我的MVC路线:

routes.MapRoute(
            name: "Tracker",
            url: "{r}",
            defaults: new { controller = "Home", action = "Index", id = "" });

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

MVC版本5.2.3,.NET 4.6.1

1 个答案:

答案 0 :(得分:1)

您是否尝试过使用:VaryByHeader =“主持人”?

[HttpGet]
[OutputCache(Duration = 3600, VaryByHeader = "Host")]
public async Task<ViewResult> Index(string r)
{
   // Stuff...
}

更多信息如何以不同的方式执行此操作:

Output cache for multi-tenant application, varying by hostname and culture