在ASP.NET中,是否可以按主机名输出缓存?即varybyhost或varbyhostheader?

Pur*_*ome 7 asp.net outputcache hostheaders vary

我有一个网站,有许多主机标题.主题和数据取决于主机标头,不同的主机加载不同的外观网站.

所以让我们假设我有一个名为"Foo"的网站,它返回搜索结果.相同的代码运行下面列出的两个站点.它是相同的服务器和网站(使用主机标头)

  1. www.foo.com
  2. www.foo.com.au

现在,如果我去.com,该网站以蓝色为主题.如果我去.com.au网站,它的主题是红色.

根据主机名,相同搜索结果的数据不同:美国结果.com和澳大利亚结果.com.au.

如果我想使用OutputCaching,可以通过主机名来处理和分区吗?

我担心一个人访问该.com网站后(正确返回美国结果),第二个访问该.com.au网站并搜索相同数据的人将获得该.com网站的主题和结果.

缓存可能吗?

Reb*_*cca 11

是的,你可以"根据习惯而变化".我使用相同的:

将以下内容放在Global.asax.cs中:

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if (custom == "Host")
    {
        return context.Request.Url.Host;
    }
    return String.Empty;
}
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器中:

[OutputCache(VaryByParam = "None", VaryByCustom="Host", Duration = 14400)]
public ActionResult Index()
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*ard 5

查看OutputCache指令的VaryByCustom参数。

要定义调用 VaryByCustom 时会发生什么,您需要覆盖方法 GetVaryByCustomString:

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if(custom == "Your_Custom_Value")
    {
        // Do some validation.
        // Return a string for say, .com, or .com.au

    }
    return String.Empty;
}
Run Code Online (Sandbox Code Playgroud)

关键是为每个要缓存的实例返回一个字符串值。在您的情况下,您的重写方法需要从 URL 中去除“.com”或“.com.au”部分并返回它。每个不同的值产生不同的缓存。

HTH