[英]Asp.Net Server-side Output Cache gets hit every request (HttpHandler)
我下面有这段非常简单的代码。
我已经尝试了好几种方法,但我不明白为什么服务器端输出缓存在http:// localhost上不起作用。 下面是“高速缓存设置”为了不看到调试输出窗格中HIT的最后一次尝试。
真让我发疯! 如何防止HIT ...?! 当我打开开发人员工具并选中“禁用缓存”时,我期望缓存的服务器端副本不会在“调试输出”窗格中看到HIT。
我在Windows 8上,但是即使在另一个Windows版本(/ IIS版本)上,我也无法想象最终的代码会有所不同。
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Web;
namespace WebApplication1
{
/// <summary>
/// Summary description for MyHandler
/// </summary>
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Debug.WriteLine("HIT"+DateTime.Now.ToLongTimeString());
context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(5));
context.Response.Cache.SetCacheability(HttpCacheability.Server);
context.Response.Cache.SetValidUntilExpires(true);
context.Response.Cache.SetOmitVaryStar(true);
context.Response.Cache.VaryByParams["none"] = true;
context.Response.Cache.SetMaxAge(new TimeSpan(0, 5, 0));
// Just here for testing purposes
const string url = "http://otherserver/image.png";
using (var client = new HttpClient())
{
var task = client.GetStreamAsync(url);
task.Wait();
task.Result.CopyTo(context.Response.OutputStream);
context.ApplicationInstance.CompleteRequest();
}
}
public bool IsReusable
{
get { return true; }
}
}
}
事实证明, ApplicationInstance.CompleteRequest()
导致了我的处境。 根据MSDN,它:
使ASP.NET绕过HTTP管道执行链中的所有事件和筛选,并直接执行EndRequest事件。
如您所见,该处理程序正在中间的某个位置执行,在调用ApplicationInstance.CompleteRequest()
它会跳过所有内容并直接转到Send请求(或内部的CompleteRequest()
)。
发生这种情况时,它还会跳过“更新缓存”事件。 这是更新请求缓存的地方; 服务器端输出缓存项将添加到的位置...
因此,当您认为自己在HttpHandler
完成操作时,请注意ApplicationInstance.CompleteRequest()
会执行什么操作!
另一个有趣的读物: https : //weblog.west-wind.com/posts/2009/May/21/Dont-use-ResponseEnd-with-OutputCache
祝您缓存愉快!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.