Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing ETag Support in ASP.NET MVC4 WebAPI

In the latest ASP.NET MVC4 beta, how would you support conditional GET support via ETags? The ActionFilter would need to be able to complete the request to generate the ETag for the returned resource in order to compare to the If-None-Match header in the request. And then, regardless of whether the incoming ETag in the If-None-Match header was the same as the generated ETag, add the generated ETag to the ETag response header. But with ASP.NET MVC4, I have no idea where to begin. Any suggestions?

like image 871
Bullines Avatar asked Apr 28 '12 17:04

Bullines


People also ask

How do I use ETag in Web API?

First, you retrieve the current entity data by using a GET request that includes the If-Match request header. The ETag information is returned along with the entity content. Then, you send a PUT update request that includes the If-Match request header with the ETag information from the previous GET request.

Why are the FromBody and FromUri attributes needed in asp net Web API?

The [FromUri] attribute is prefixed to the parameter to specify that the value should be read from the URI of the request, and the [FromBody] attribute is used to specify that the value should be read from the body of the request.

How do I use FromUri in Web API?

Using [FromUri] To force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. The following example defines a GeoPoint type, along with a controller method that gets the GeoPoint from the URI.

How do I get an ETag value?

Common methods of ETag generation include using a collision-resistant hash function of the resource's content, a hash of the last modification timestamp, or even just a revision number.


1 Answers

Personally, I'm not a fan of "framework magic" and prefer plain old code in the web methods, else we end up with something more akin to WCF, yuk.

So, within your Get web method, manually create the response like so:

var response = this.Request.CreateResponse(HttpStatusCode.OK, obj);
string hash = obj.ModifiedDate.GetHashCode().ToString();

response.Headers.ETag =
    new EntityTagHeaderValue(String.Concat("\"", hash, "\""), true);

return response;

Please note that the ETag produced from the hash code of the timestamp is purely illustrative of a weak entity tagging system. It also shows the additional quotes required.

like image 98
Luke Puplett Avatar answered Oct 26 '22 04:10

Luke Puplett