Is there a guaranteed way to cancel a post when using HttpClient? I currently have a call do PostAsync that I am attempting to cancel using a cancellationToken, but it appears that it does not actually abort/stop the operation. I still can see that the image I am uploading is posted properly.
Am I doing something wrong here or is it possible that HttpClient is not processing the cancellation token until after the upload?
var sc = new StreamContent(uploadFile.Data);
content.Add(sc, uploadFile.FieldName, uploadFile.FileName);
var request = new HttpRequestMessage
{
RequestUri = new Uri(ApiImageUrlUpload),
Content = content
};
request.Headers.TryAddWithoutValidation("User-Agent", _sessionManager.UserAgent);
request.Headers.TransferEncodingChunked = true;
using(cancellationToken.Register(() => httpClient.CancelPendingRequests()))
httpResponse = await HttpClient.PostAsync(new Uri(ApiImageUrlUpload), content, cancellationToken);
Try this code example
You could dispose of the request object manually which should throw an
ObjectDisposedException
and cancel any network activity.