-
-
Save benfoster/3150615 to your computer and use it in GitHub Desktop.
static Dictionary<int, string> etags = new Dictionary<int, string>(); | |
// GET api/site/5 | |
public HttpResponseMessage Get(int id, HttpRequestMessage request) | |
{ | |
var etag = request.Headers.IfNoneMatch; // strange that we can't do FirstOrDefault() | |
if (etag != null && etags.ContainsKey(id)) | |
{ | |
if (etags[id] == etag.ToString()) | |
{ | |
var notModified = new HttpResponseMessage(HttpStatusCode.NotModified); | |
return notModified; | |
} | |
} | |
var site = session.Load<Site>(id); | |
if (site == null || site.Deleted) | |
ThrowSiteNotFound(); | |
var metadata = session.Advanced.GetMetadataFor(site); | |
var siteEtag = metadata.Value<string>("@etag"); | |
etags[id] = siteEtag; | |
var response = Request.CreateResponse<Site>(HttpStatusCode.OK, site); | |
response.Headers.ETag = new EntityTagHeaderValue("\"" + siteEtag + "\""); | |
response.Content.Headers.LastModified = metadata.Value<DateTime>("Last-Modified"); | |
return response; | |
} |
We would probably want to use a RavenDB listener to update the Etag when an entity is changed.
I am not sure if your situation fits in such an approach but handling the HTTP caching with a Message Handler would be better since it will terminate the request immediately but in your case the request already reached to the controller action.
The problem with RavenDb ETAG is imho that you get it only for entities but not for collections. Use CacheCow instead.
Can we inject dependencies into a message handler?
I'll have a look at CacheCow
no, not currently. Message Handler pipeline doesn't look for dependencies through DI.
Bu you can grab the the dependency inside a message handler as shown below:
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) {
var dependencyScope = request.GetDependencyScope();
var service = dependencyScope.GetService(typeof(?));
return base.SendAsync(request, cancellationToken);
}
Okay. Good to know. I've just added CacheCow as suggested and this looks like it will be much easier.
Thanks.