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



我的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(。

因此,缓存应因子域而异。

但是,该完全限定 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 }
);

MVC 版本 5.2.3、.NET 4.6.1

你有没有尝试过使用: VaryByHeader = "Host" ?

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

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

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

最新更新