For the past few days, I have been thinking about the output cache in asp.net. In my task, I need to implement an output cache for a very large project. After hours of searching, I did not find any examples.
The most popular way to use the output cache is declarative, in which case you need to write something like this on the page you want to cache.
But if you need to cache the entire site, you should write it on all pages or main pages of the project. This is madness. In this case, you cannot store the entire configuration in one place. All pages have their own configurations.
Global.asax can help me, but my site contains about 20 web programs and ~ 20 global.asax files. And I do not want to copy the same code for each project.
For these reasons, I decided to create an HTTPModule. In the Init method, I subscribe to two events:
public void Init(HttpApplication app)
{
app.PreRequestHandlerExecute += new EventHandler(OnApplicationPreRequestHandlerExecute);
app.PostRequestHandlerExecute += new EventHandler(OnPostRequestHandlerExecute);
}
In the "OnPostRequestHandlerExecute" method, I configured output caching options for each new request:
public void OnPostRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpCachePolicy policy = app.Response.Cache;
policy.SetCacheability(HttpCacheability.Server);
policy.SetExpires(app.Context.Timestamp.AddSeconds((double)600));
policy.SetMaxAge(new TimeSpan(0, 0, 600));
policy.SetValidUntilExpires(true);
policy.SetLastModified(app.Context.Timestamp);
policy.VaryByParams.IgnoreParams = true;
}
In the "OnApplicationPreRequestHandlerExecute" method, I set the calback method to check the caching:
public void OnApplicationPreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Context.Response.Cache.AddValidationCallback(new HttpCacheValidateHandler(Validate), app);
}
And the last part is the callback verification method:
public void Validate(HttpContext context, Object data, ref HttpValidationStatus status)
{
if (context.Request.QueryString["id"] == "5")
{
status = HttpValidationStatus.IgnoreThisRequest;
context.Response.Cache.AddValidationCallback(new HttpCacheValidateHandler(Validate), "somecustomdata");
}
else
{
status = HttpValidationStatus.Valid;
}
}
To attach my HttpModule, I use the software attach method:
[assembly: PreApplicationStartMethod(typeof(OutputCacheModule), "RegisterModule")]
This method works fine, but I want to know if there are other ways to do this. Thank you