gpt4 book ai didi

c# - 如何使用 IHttpHandler 启用 OutputCache

转载 作者:太空宇宙 更新时间:2023-11-03 14:30:44 26 4
gpt4 key购买 nike

我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com