我有一个 IHttpHandler
,我想连接到 OutputCache 支持,这样我就可以将缓存数据卸载到 IIS 内核。我知道 MVC 必须以某种方式执行此操作,我在 OutputCacheAttribute
中找到了它:
public override void OnResultExecuting(ResultExecutingContext filterContext) {
if (filterContext == null) {
throw new ArgumentNullException("filterContext");
}
// we need to call ProcessRequest() since there's 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);
}
}
但不确定如何将其应用于 IHttpHandler
。尝试过这样的事情,但这当然行不通:
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;
}
}
}
最佳答案
必须这样做:
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;
}
}
}
关于c# - 如何使用 IHttpHandler 启用 OutputCache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2691080/