Is there a way to set the value of an OutputCache based on a cookie value?
For simplicities sake, this is my method
[OutputCache(Duration = 600, VaryByParam = "None", VaryByCustom = "ztest")]
public ViewResult Index()
{
return View();
}
My Global.asax has this (in order to override the GetVaryByCustomString method
public override string GetVaryByCustomString(HttpContext context, string custom)
{
if (custom == "ztest")
{
HttpCookie ztest = context.Request.Cookies["ztest"];
if (ztest != null)
{
return ztest.Value;
}
}
return base.GetVaryByCustomString(context, custom);
}
I can verify that my browser has the ztest cookie, but when I debug the Index method, I hit the breakpoint every time (meaning that the cache isn't working).
The HttpResponse has no outbound cookies, so this point would not apply: https://msdn.microsoft.com/en-us/library/system.web.httpcookie.shareable(v=vs.110).aspx
If a given HttpResponse contains one or more outbound cookies with Shareable is set to false (the default value), output caching will be suppressed for the response. This prevents cookies that contain potentially sensitive information from being cached in the response and sent to multiple clients. To allow a response containing cookies to be cached, configure caching normally for the response, such as using the OutputCache directive or MVC's [OutputCache] attribute, and set all outbound cookies to have Shareable set to true.
The subtle answer is no.
The Explained answer is as follows:
The reason output cache doesn't play nice with cookies
So the reason the output cache will not cache a response with cookies is that a cookie could be user-specific (e.g. authentication, analytical tracking, etc.). If one or more cookies with the property
HttpCookie.Shareable = false
, then the output cache considers the response uncacheable.Solution:
There are some workarounds though, The output cache caches the response headers and content together and doesn't provide any hooks to modify these before sending them back to the user.However,there is a way to provide the ability to change before cached response's headers before they are sent back to the user. One of them requires the Fasterflect nuget package.
I have an example of code:
Wire it up this way:
And use it this way:
I don't know if it answers you question, but I hope it points to the right direction.