Using Etags In Asp.net Mvc
There are two parts to taking advantage of ETags in ASP.NET MVC (or really any other web framework):
- Set ETags when returning a response
- Checking a provided ETag on a request
##Setting ETags on the Response
The syntax is the easy part:
Response.Cache.SetETag(responseETag);
More difficult, is deterministically creating the ETag value (responseETag
above). The ETag should be a representation of the response content. If the response content doesn’t change, then the same ETag value should always be returned. This could be simply a last modified date, generated by hashing a file, or based off of some database value.
Also, another tip is that you need to set the cacheability of the response, otherwise by default it’s “private” and the ETag won’t be set in the response:
Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
##Checking Request ETag in the Request Here, you should check the ‘If-None-Match’ header that is sent automatically by the browser if the url has been previously requested and cached by the user. This value is then compared with the ETag value of the expected response. If the two match, then the server should return the HTTP status code 304.
Example code:
##Full Example So putting it all together:
blog comments powered by Disqus