I am uploading an image with HttpClient.PostAsync()
on my Windows Phone 8 app. The user has the option to cancel this upload via a UI button.
To cancel the POST request, I set a CancellationToken
. But this doesn't work. After the cancellation request, I see still see the upload taking place in my proxy and it is evident that the request was ignored. My code:
using (var content = new MultipartFormDataContent())
{
var file = new StreamContent(stream);
file .Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = "filename.jpg",
};
file.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
content.Add(file);
await httpclient.PostAsync(new Uri("myurl", UriKind.Absolute), content,
cancellationToken);
}
Please also note that I have a CancellationTokenSource
for the CancellationToken
. After the user clicks on the Cancel button, tokensource.Cancel()
is called. Also, the images in my testcase are from 1 to 2 MB (not that big).
So, is there a way to cancel an HttpClient
POST request?
CancelationTokenSource
will cancel the underlying operation. It depends upon the implementation of the underlying operation (in this caseSendAsync
method). Operation could be canceled immediately, or after few seconds, or never." So, based on that, it appears that after making thePostAsync()
request, you may need to checkcancellationToken.IsCancellationRequested
, and if true, callDeleteAsync()
on the uploaded image. – ScapegracePostAsync()
call, it appears to be the latter.) – Scapegrace