Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 893
Pure.Krome Avatar asked May 11 '10 01:05

Pure.Krome


2 Answers

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();
}
like image 120
Rebecca Avatar answered Oct 06 '22 00:10

Rebecca


Check out the VaryByCustom parameter of the OutputCache directive.

To define what happens when VaryByCustom is called, you need to override the method 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;
}

The key is to return a string value for each instance you want to cache. In your case, your overrided method would need to strip the ".com" or ".com.au" part from the URL and return it. Each different value produces a different cache.

HTH

like image 36
Richard Avatar answered Oct 06 '22 01:10

Richard