Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel an 'HttpClient' POST request

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?

like image 425
Joehl Avatar asked Sep 28 '22 07:09

Joehl


1 Answers

try
{
    var client = new HttpClient();

    var cts = new CancellationTokenSource();
    cts.CancelAfter(3000); // 3 seconds

    var request = new HttpRequestMessage();

    await client.PostAsync(url, content, cts.Token);
}
catch(OperationCanceledException ex)
{
    // timeout has been hit
}
like image 61
xRed Avatar answered Oct 06 '22 00:10

xRed