Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I support ETags in ASP.NET MVC?

How do I support ETags in ASP.NET MVC?

like image 899
Patrick Gidich Avatar asked Jun 02 '09 02:06

Patrick Gidich


People also ask

Where are Etags stored?

Whenever a resource is requested (via its URL), the data and ETag are retrieved and stored in the Web cache, and the ETag is sent along with subsequent requests. If the ETag at the server has not changed, a "Not Modified" message is returned, and the cached data are used. See Web cache and browser cache.

Can we use view state in MVC?

ASP.NET MVC does not use ViewState in the traditional sense (that of storing the values of controls in the web page). Rather, the values of the controls are posted to a controller method.


2 Answers

@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
}
like image 145
jaminto Avatar answered Oct 23 '22 09:10

jaminto


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

like image 20
Elijah Glover Avatar answered Oct 23 '22 10:10

Elijah Glover