Just by having ETag or Last-Modified time, your GET method will be cached in the browser. You can easily test this using fiddler.
In this post I am going to write a conditional cache logic based on ETag and/or LastModified. In the following code Product object has two additional fields : ETag and LastModifiedDate, based on this (both or eather) field, we will determine if we need to suppress Entity Body and accordingly set the response status to NotModified.
public Product GetProductRestStyle(string id) { OutgoingWebResponseContext outgoingResponse = WebOperationContext.Current.OutgoingResponse; IncomingWebRequestContext incomingRequest = WebOperationContext.Current.IncomingRequest; //retrieve product object from any repository Product product = GetProduct(Convert.ToInt32(id)); if(product == null) { outgoingResponse.SetStatusAsNotFound(); return null; } //Product object contains LastModifiedDate and ETag, which we will compare in the incomingRequest //and if it is same we will supress the response body CheckModifiedSince(incomingRequest, outgoingResponse, product.LastModifiedDate); CheckETag(incomingRequest, outgoingResponse, product.ETag); //Set LastModifiedDate and ETag on the outgoing response outgoingResponse.ETag = product.ETag.ToString(); outgoingResponse.LastModified = product.LastModifiedDate; //Give a cache hint //Resource will expire in 10 sec outgoingResponse.Headers.Add(HttpResponseHeader.CacheControl, "max-age=10"); return product; } private static void CheckETag(IncomingWebRequestContext incomingRequest, OutgoingWebResponseContext outgoingResponse, Guid ServerETag) { string test = incomingRequest.Headers[HttpRequestHeader.IfNoneMatch]; if (test == null) return; Guid? eTag = new Guid( test); if (eTag != ServerETag) return; outgoingResponse.SuppressEntityBody = true; outgoingResponse.StatusCode = HttpStatusCode.NotModified; } private static void CheckModifiedSince(IncomingWebRequestContext incomingRequest, OutgoingWebResponseContext outgoingResponse, DateTime serverModifiedDate) { DateTime modifiedSince = Convert.ToDateTime(incomingRequest.Headers[HttpRequestHeader.LastModified]); if (modifiedSince != serverModifiedDate) return; outgoingResponse.SuppressEntityBody = true; outgoingResponse.StatusCode = HttpStatusCode.NotModified; }
The above code will be useful in the following conditions:
In the case where the client cannot tolerate a stale cache and a "hint" is not good enough, they may issue a request to the server, if the cache is still fresh, the server will send a 304 "Not Modified" response with no entity body. The client can then safely source the data from it’s cache.
Another scenario is the case where the client abides by the caching hint, but the cache is expired. As opposed to simply throwing away the cache, the client can issue a Conditional GET to see if the cache is still good.
No comments:
Post a Comment