0

我有一个返回 XML 的自定义 HttpHandler。我想添加缓存条件并在没有更改但“If-Modified-Since”标头从未出现在我的请求中始终为空时返回 304 有人可以帮助我吗?

public class ResourceHandler : IHttpHandler
{
  public void ProcessRequest(HttpContext context)
  {
        TimeSpan freshness = new TimeSpan(0, 0, 0, 3);
        context.Response.Cache.SetExpires(DateTime.Now.Add(freshness));
        context.Response.Cache.SetMaxAge(freshness);
        context.Response.Cache.SetCacheability(HttpCacheability.Private);


???? Always is NULL
    string rawIfModifiedSince = context.Request.Headers.Get("If-Modified-Since");
    if (string.IsNullOrEmpty(rawIfModifiedSince))
    {
      // Set Last Modified time
      context.Response.Cache.SetLastModified(XML last modified date);
    }
    else
    {
      DateTime ifModifiedSince = DateTime.Parse(rawIfModifiedSince);

      // HTTP does not provide milliseconds, so remove it from the comparison
      if (resource.LastModifiedDate.AddMilliseconds(
                  -resource.LastModifiedDate.Millisecond) >= ifModifiedSince)
      {
          // The requested file has not changed
          context.Response.StatusCode = 304;
          return;
      }
    }

    ….. XML output 
            XmlSerializer xr = new XmlSerializer(typeof(XElement));
            MemoryStream mr = new MemoryStream();

            XElement xml = OperatorXmlManager.Load(usr.SDEID, lang);


            xr.Serialize(mr, xml);
            byte[] OutXmlByte = mr.ToArray();

            context.Response.OutputStream.Write(OutXmlByte, 0, OutXmlByte.Length/4);
            context.Response.ContentType = "text/xml";

  }

  public bool IsReusable
  {
    get { return true; }
  }
}
4

1 回答 1

0

根据RFC 2616 HTTP/1.1 第 14.25 节

为了在发送 If-Modified-Since 标头字段以进行缓存验证时获得最佳结果,建议客户端尽可能使用在先前的 Last-Modified 标头字段中收到的确切日期字符串。

因此,请尝试在您的响应中设置 Last-Modified 标头。

于 2013-11-08T15:51:50.093 回答