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

con*_*att 9 .net asp.net-mvc caching outputcache asp.net-mvc-5

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

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

我在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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

所以缓存应该在子域上有所不同.

但是,该完全限定URL上的任何"路径"都应共享相同的缓存.所以下面应该读取相同的输出缓存:

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

有一个令人筋疲力尽的原因,为什么会这样,但简而言之,它是一个SPA应用程序,而"路径"实际上只是一个跟踪器.这不能更改为查询字符串.

当路径(跟踪器)改变时,新访问索引方法.我可以通过调试器告诉我.作为注释,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 }
        );
Run Code Online (Sandbox Code Playgroud)

MVC版本5.2.3,.NET 4.6.1

小智 1

您是否尝试过使用:VaryByHeader =“Host”?

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

您可以在此处找到如何以不同方式执行此操作的更多信息:

多租户应用程序的输出缓存,因主机名和文化而异