How do I support ETags in ASP.NET MVC?

asp.net MvcEtag

asp.net Mvc Problem Overview


How do I support ETags in ASP.NET MVC?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

@Elijah Glover's answer is part of the answer, but not really complete. This will set the ETag, but you're not getting the benefits of ETags without checking it on the server side. You do that with:

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

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);

So a full 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
}

Solution 2 - asp.net Mvc

ETAG's in MVC are the same as WebForms or HttpHandlers.

You need a way of creating the ETAG value, the best way I have found is using a File MD5 or ShortGuid.

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

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPatrick GidichView Question on Stackoverflow
Solution 1 - asp.net MvcjamintoView Answer on Stackoverflow
Solution 2 - asp.net MvcElijah GloverView Answer on Stackoverflow