asp.netoutputcachehostheadersvary

In ASP.NET, is it possible to output cache by host name? ie varybyhost or varbyhostheader?


I've got a website that has a number of host headers. The theme and data depend on the host header, and different hosts load different looking sites.

So let's imagine I have a website called "Foo" that returns search results. The same code runs both sites listed below. It is the same server and website (using Host Headers)

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

Now, if I go to .com, the site is themed in blue. If I go to the .com.au site, it's themed in red.

And the data is different for the same search result, based on the host name: US results for .com and Australian results for .com.au.

If I wish to use OutputCaching, can this be handled and partitioned by the host name?

I'm concern that after a person goes to the .com site, (correctly returning US results) that a second person visiting the .com.au site and searching for the same data will get the theme and results for the .com site.

Is caching possible?


Solution

  • Yes, you can "vary by custom". I am using the same:

    Place the following in your Global.asax.cs:

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

    Then in your controller:

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