How to enable OutputCache using IHttpHandler
I have IHttpHandler
one that I would like to hook into OutputCache support so that I can load the cached data into the IIS core. I know MVC has to do it somehow, I found this in OutputCacheAttribute
:
public override void OnResultExecuting(ResultExecutingContext filterContext) {
if (filterContext == null) {
throw new ArgumentNullException("filterContext");
}
// we need to call ProcessRequest() since there no other way to set the Page.Response intrinsic
OutputCachedPage page = new OutputCachedPage(_cacheSettings);
page.ProcessRequest(HttpContext.Current);
}
private sealed class OutputCachedPage : Page {
private OutputCacheParameters _cacheSettings;
public OutputCachedPage(OutputCacheParameters cacheSettings) {
// Tracing requires Page IDs to be unique.
ID = Guid.NewGuid().ToString();
_cacheSettings = cacheSettings;
}
protected override void FrameworkInitialize() {
// when you put the <%@ OutputCache %> directive on a page, the generated code calls InitOutputCache() from here
base.FrameworkInitialize();
InitOutputCache(_cacheSettings);
}
}
But not sure how to apply this to IHttpHandler
. Tried something like this, but of course it doesn't work:
public class CacheTest : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
OutputCacheParameters p = new OutputCacheParameters { Duration = 3600, Enabled = true, VaryByParam = "none", Location = OutputCacheLocation.Server };
OutputCachedPage page = new OutputCachedPage(p);
page.ProcessRequest(context);
context.Response.ContentType = "text/plain";
context.Response.Write(DateTime.Now.ToString());
context.Response.End();
}
public bool IsReusable
{
get
{
return true;
}
}
}
+2
a source to share
1 answer
This should be done as follows:
public class CacheTest : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
TimeSpan expire = new TimeSpan(0, 0, 5, 0);
DateTime now = DateTime.Now;
context.Response.Cache.SetExpires(now.Add(expire));
context.Response.Cache.SetMaxAge(expire);
context.Response.Cache.SetCacheability(HttpCacheability.Server);
context.Response.Cache.SetValidUntilExpires(true);
context.Response.ContentType = "text/plain";
context.Response.Write(DateTime.Now.ToString());
}
public bool IsReusable
{
get
{
return true;
}
}
}
+1
a source to share