我有一个返回 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; }
}
}