Skip to content

Instantly share code, notes, and snippets.

@jfversluis
Created May 29, 2018 06:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfversluis/adebdad542cac503175a0d1ff870254b to your computer and use it in GitHub Desktop.
Save jfversluis/adebdad542cac503175a0d1ff870254b to your computer and use it in GitHub Desktop.
Handling the ETag client-side
public class EtagHttpClientHandler : HttpClientHandler
{
private Dictionary<string, string> _etagDictionary = new Dictionary<string, string>();
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// See if we have a ETag for this endpoint and add it to the request
_etagDictionary.TryGetValue(request.RequestUri.ToString(), out var etag);
if (!string.IsNullOrWhiteSpace(etag))
{
request.Headers.IfNoneMatch.Clear();
request.Headers.IfNoneMatch.Add(new EntityTagHeaderValue(etag));
}
// Everything before the base call is the request
var responseMessage = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
// Here we can handle the response
if (responseMessage.IsSuccessStatusCode)
{
// If a ETag is provided with the response, cache it for future requests
if (!string.IsNullOrWhiteSpace(responseMessage.Headers.ETag?.Tag))
_etagDictionary.Add(responseMessage.RequestMessage.RequestUri.ToString(), responseMessage.Headers.ETag?.Tag);
}
return responseMessage;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment