Cache-Control header cannot be set properly in ASP.NET 2.0 - A solution
Do you know that you cannot set Cache-Control: max-age header in
ASP.NET 2.0? No matter how many combinations you try, you will
always end up with "max-age=0" for sure.
I found solution to the SetMaxAge problem in HttpCachePolicy.
Here's the code of the function in HttpCachePolicy
(decompiled):
public void SetMaxAge(TimeSpan
delta)
{
if (delta < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException("delta");
}
if (HttpCachePolicy.s_oneYear < delta)
{
delta = HttpCachePolicy.s_oneYear;
}
if (!this._isMaxAgeSet || (delta < this._maxAge))
{
this.Dirtied();
this._maxAge = delta;
this._isMaxAgeSet = true;
}
}
Someone is setting maxAge already to 0. So, if I assign a higher
value it does not get set.
I am not sure why the "(delta < this._maxAge)" condition is
necessary. If I somehow set a lower maxAge, I can never increase
it!
So, I have made an HttpModule which does this:
void context_EndRequest(object
sender, EventArgs e) {
if (HttpContext.Current.Items.Contains("SetMaxAge"))
{
FieldInfo maxAge =
HttpContext.Current.Response.Cache.GetType().GetField("_maxAge",
BindingFlags.Instance | BindingFlags.NonPublic);
maxAge.SetValue(HttpContext.Current.Response.Cache,
(TimeSpan)HttpContext.Current.Items["SetMaxAge"]);
//
SetMaxAge does not
work.
//HttpContext.Current.Response.Cache.SetMaxAge((TimeSpan)HttpContext.Current.Items["SetMaxAge"]);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);
HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddMinutes(5));
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
}
}
If someone sets "SetMaxAge" to a Timespan in the Context.Items,
it will get set to the response and the end of the request. This
ensures, no matter who does what with cache object, maxAge will
definitely be set.
Although this is not a Atlas specific problem, it seems to be a
problem in ASP.NET 2.0 itself.
Now I can cache AJAX call responses on the browser and prevent
roundtrips.