2017-02-15 81 views
0

我有这个非常简单的前面一段代码。Asp.Net服务器端输出缓存得到了每一个请求(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; } 
     } 
    } 
} 

回答

0

事实证明,ApplicationInstance.CompleteRequest()是在我的情况造成的痛苦。根据MSDN它:

导致ASP.NET绕过HTTP管道执行过程中的所有事件和筛选,并直接执行EndRequest事件。

这是被在中间的某个地方执行Asp.Net pipeline flow

Asp.Net pipeline flow

的处理程序,你可以看到,并呼吁ApplicationInstance.CompleteRequest()后,它会跳过一切,并直接发送请求(或CompleteRequest()内部) 。

发生这种情况时,它也会跳过“更新缓存”事件。这是请求缓存被更新的地方;服务器端输出缓存项目将被添加...

因此,请注意当您认为您完成HttpHandler时,ApplicationInstance.CompleteRequest()会执行什么操作!

另一个有趣的阅读:https://weblog.west-wind.com/posts/2009/May/21/Dont-use-ResponseEnd-with-OutputCache

快乐缓存!