Created
May 29, 2018 06:57
-
-
Save jfversluis/adebdad542cac503175a0d1ff870254b to your computer and use it in GitHub Desktop.
Handling the ETag client-side
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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