How to support ETags in ASP.NET MVC?

How do I support ETags in ASP.NET MVC?

+60
asp.net-mvc etag
Jun 02 '09 at 2:22
source share
2 answers

@Elijah Glover's answer is part of the answer, but is not really complete. This will install the ETag, but you will not get the benefits of ETag without checking it on the server side. You do this with:

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

In addition, another tip is that you need to set the cacheability of the response, otherwise it will be closed by default and ETag will not be set in the response:

 Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate); 

So a complete example:

 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 } 
+42
Jul 15 '13 at 16:08
source share

ETAGs in MVC are the same as WebForms or HttpHandlers.

You need a way to create an ETAG value, the best way I've found is to use an MD5 file or ShortGuid .

Since .net accepts the string as ETAG, you can easily set it using

 String etag = GetETagValue(); //eg "00amyWGct0y_ze4lIsj2Mw" Response.Cache.SetETag(etag); 

Video from MIX , at the end they use ETAG with REST

+30
Jun 02 '09 at 2:32
source share



All Articles