相关疑难解决方法(0)

正确中止或取消PostAsync

使用HttpClient时是否有保证取消帖子的方法?我目前有一个调用PostAsync,我试图使用cancellationToken取消,但它似乎并没有实际中止/停止操作.我仍然可以看到我上传的图片已正确发布.

我在这里做错了还是HttpClient可能在上传之前没有处理取消令牌?

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);
Run Code Online (Sandbox Code Playgroud)

.net c# dotnet-httpclient xamarin

6
推荐指数
1
解决办法
974
查看次数

取消对'HttpClient.SendAsync()'的调用

可以取消拨打电话HttpClient.SendAsync()吗?

我发送的数据如下:

var requestMessage = new HttpRequestMessage(HttpMethod.Post, "some url");
var multipartFormDataContent = new MultipartFormDataContent();
// ... construction of the MultipartFormDataContent. It contains form data + picture file
requestMessage.Content = multipartFormDataContent;
var response = await client.SendAsync(requestMessage).ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)

此代码完美无缺,但我需要能够根据用户需求取消请求.这可能吗?

我看到有一个超载SendAsync接受了CancellationToken但我不知道如何使用它.我也知道一个叫做的属性IsCancellationRequested,表明请求是否已被取消.但是,如何实际取消请求呢?

.net c# cancellation dotnet-httpclient

3
推荐指数
1
解决办法
4908
查看次数

标签 统计

.net ×2

c# ×2

dotnet-httpclient ×2

cancellation ×1

xamarin ×1