Published

15 July 2013
 / 

Category

Development
 / 

Tags

There are two parts to taking advantage of ETags in ASP.NET MVC (or really any other web framework):

  1. Set ETags when returning a response
  2. 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:

var requestedETag = Request.Headers["If-None-Match"];
if (requestedETag == eTagOfContentToBeReturned)
        return new HttpStatusCodeResult(HttpStatusCode.NotModified);

Full Example

So putting it all together:

public ActionResult Test304(string input)
{
    var requestedETag = Request.Headers["If-None-Match"];
    var responseETag = LookupEtagFromInput(input); // lookup or generate etag however you want
    if (requestedETag == responseETag)
        return new HttpStatusCodeResult(HttpStatusCode.NotModified);

    Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
    Response.Cache.SetETag(responseETag);
    return GetResponse(input); // do whatever work you need to obtain the result
}


blog comments powered by Disqus