I have a custom HttpHandler which return XML. I want to add cache condition and return 304 when there is no changes but "If-Modified-Since" header never appear in my Request always is null can somebody help me.
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; }
}
}
According to RFC 2616 HTTP/1.1 section 14.25 :
To get best results when sending an If-Modified-Since header field for cache validation, clients are advised to use the exact date string received in a previous Last-Modified header field whenever possible.
Hence, try to set Last-Modified header in you response.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.