Skip to content

Instantly share code, notes, and snippets.

@GeorgeTsiokos
Last active August 15, 2017 14:26
Show Gist options
  • Save GeorgeTsiokos/c6afc9a809ab74858dbe71278a45cf86 to your computer and use it in GitHub Desktop.
Save GeorgeTsiokos/c6afc9a809ab74858dbe71278a45cf86 to your computer and use it in GitHub Desktop.
Return Gone when IsCancellationRequested
/// <summary>
/// Returns the specified code when the CancellationToken is canceled
/// </summary>
public sealed class CancellationDelegatingHandler : DelegatingHandler
{
readonly HttpStatusCode _canceledCode;
public CancellationDelegatingHandler(HttpStatusCode canceledCode = HttpStatusCode.Gone)
{
_canceledCode = canceledCode;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpResponseMessage GetResponse(Task<HttpResponseMessage> task) => cancellationToken.IsCancellationRequested ? new HttpResponseMessage(_canceledCode) : task.Result;
return base.SendAsync(request, cancellationToken).ContinueWith(GetResponse, TaskContinuationOptions.ExecuteSynchronously);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment