HttpClient PostAsync取消请求

时间:2019-02-27 09:19:40

标签: c# dotnet-httpclient

我有一个非常琐碎的案例,我想将文件上传到名为CloudConvert.com的服务中

我使用多部分表单来做到这一点,甚至还有一个示例如何在其API控制台上使用html中的多部分表单:

这是他们的示例:

<form action="https://api.cloudconvert.com/convert" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="hidden" name="apikey" value="banana-my-key">
<input type="hidden" name="inputformat" value="pdf">
<input type="hidden" name="outputformat" value="docx">
<input type="hidden" name="input" value="upload">
<input type="hidden" name="wait" value="true">
<input type="hidden" name="download" value="inline">
<input type="submit" value="Convert!">
</form>    

这是我对应的C#代码:

using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{                
    formData.Add(new StreamContent(paramFileStream), "file" );
    formData.Add(new StringContent("banana-my-key"), "apikey" );
    formData.Add(new StringContent("pdf"), "inputformat" );
    formData.Add(new StringContent("docx"), "outputformat" );
    formData.Add(new StringContent("upload"), "input");
    formData.Add(new StringContent("true"), "wait");
    formData.Add(new StringContent("inline"), "download");
    var response = await client.PostAsync("https://api.cloudconvert.com/convert", formData,new CancellationTokenSource(TimeSpan.FromSeconds(2000)).Token);
    if (!response.IsSuccessStatusCode)
    {
        return null;
    }

    return await response.Content.ReadAsStreamAsync();
}

此代码失败,例外:

System.Threading.Tasks.TaskCanceledException: The operation was canceled. ---> System.IO.IOException: Unable to read data from the transport connection: Operation canceled. ---> System.Net.Sockets.SocketException: Operation canceled
--- End of inner exception stack trace ---
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.GetResult(Int16 token)
at System.Net.Security.SslStreamInternal.<FillBufferAsync>g__InternalFillBufferAsync|38_0[TReadAdapter](TReadAdapter adap, ValueTask`1 task, Int32 min, Int32 initial)
at System.Net.Security.SslStreamInternal.ReadAsyncInternal[TReadAdapter](TReadAdapter adapter, Memory`1 buffer)
at System.Net.Http.HttpConnection

在Cloudconvert内部,我可以看到他们报告他们正在等待上传。

我在这里做错什么,似乎StreamContent没有按应有的方式在请求中进行流传输。

这里有明显的问题吗?

ps。将其html示例放在html文件中,然后以这种方式上传就可以了。

0 个答案:

没有答案