2

Question about settings of IIS7. How I can do one cache for each of bindings? For example, I have one site and three bindings for the site. I need to create three different caches for each of three bindings.

2 Answers 2

1

Use Request.Host as part of the cache key.

0

usr's answer is correct if you are manually reading from and writing to the cache. You have less direct control over the cache key with the OutputCacheAttribute, however.

Note that the OutputCacheAttribute still relies on cache keys in its implementation. In ASP.NET, each item that is cached is assigned a key through which it is looked up.

When you call a Controller Action that has an OutputCacheAttribute, a cache key is generated based on your request; for instance, if you have some VaryByParam designations, cache keys can differ for each user. Then the response your Action returns is stored in the cache under that key.

When the next request comes in, the cache key is generated and we check in the cache to see if there is already something cached under that key. If so, we just return that; otherwise, we continue with the Action.

We can have a different cache for each binding by including the host name in the cache key. If you're using OutputCacheAttribute, you can override it to allow varying the cache by host:

public override string GetVaryByCustomString(HttpContext context, string customVary)
{
    if(customVary == "Host")
    {
        return context.Request.Url.Host;
    }
    // other behaviors here if necessary
    return "";
}

This will allow the cache key to be dynamically modified to include the host name through which the site is accessed. This means that if you have three different bindings, you will have three different cache keys (assuming no other varying parameters).

Here's how to modify your Controller Action:

[MyOutputCache(VaryByParam = "None", VaryByCustom = "Host", Duration = 7200)]
public ActionResult Index()
{
    // ...
    return View();
}

Notice the inclusion of VaryByCustom = "Host", which is then seen by your overriden OutputCacheAttribute's GetVaryByCustomString() method and thus included in the cache key that is used.

2
  • 1
    Thanks Maxim! It works! So I found one more explanation like your explanation
    – Dmitresky
    Commented Nov 26, 2012 at 16:21
  • @DmitryBLR I'm glad to hear it helped! Good luck. Commented Nov 27, 2012 at 3:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.