Skip to content

Instantly share code, notes, and snippets.

@benfoster
Created July 20, 2012 13:01
Show Gist options
  • Save benfoster/3150615 to your computer and use it in GitHub Desktop.
Save benfoster/3150615 to your computer and use it in GitHub Desktop.
Setting response properties
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;
}
@AlexZeitler
Copy link

var response = Request.CreateResponse(HttpStatusCode.OK, site); // HttpRequestMessageExtensions in System.Net.Http
return response;

@tugberkugurlu
Copy link

With The way as Alex suggested, you will get the Conneg OOB as well.

@benfoster
Copy link
Author

Thanks.

@benfoster
Copy link
Author

We would probably want to use a RavenDB listener to update the Etag when an entity is changed.

@tugberkugurlu
Copy link

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.

@AlexZeitler
Copy link

The problem with RavenDb ETAG is imho that you get it only for entities but not for collections. Use CacheCow instead.

@benfoster
Copy link
Author

Can we inject dependencies into a message handler?

@benfoster
Copy link
Author

I'll have a look at CacheCow

@tugberkugurlu
Copy link

no, not currently. Message Handler pipeline doesn't look for dependencies through DI.

@tugberkugurlu
Copy link

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

@benfoster
Copy link
Author

Okay. Good to know. I've just added CacheCow as suggested and this looks like it will be much easier.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment