【问题标题】:HttpClient.PutAsync finish immediately with no responseHttpClient.PutAsync 立即结束,没有响应
【发布时间】:2015-02-23 14:22:02
【问题描述】:

我尝试使用以下代码将使用 PUT 方法的文件上传到 http 服务器(Apache Tika)

private static async Task<string> send(string fileName, string url)
{
    using (var fileStream = File.OpenRead(fileName))
    {
        var client = new HttpClient();

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));

        var content = new StreamContent(fileStream);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

        var response = await client.PutAsync(url, content);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }
}

在 Main 中,方法是这样调用的:

private static void Main(string[] args)
{
    // ...

    send(options.FileName, options.Url).
        ContinueWith(task => Console.WriteLine(task.Result));
}

作为响应,服务器应返回 HTTP 200 和文本响应(已解析的 pdf 文件)。我已经用 Fiddler 检查了这种行为,就服务器而言它工作正常。

不幸的是,调用 PutAsync 方法后执行完成。

我做错了什么?

【问题讨论】:

    标签: c# async-await .net-4.5 dotnet-httpclient


    【解决方案1】:

    您正在从控制台应用程序执行此操作,该应用程序将在您调用 send 后终止。您必须在其上使用 WaitResult 以使 Main 不会终止:

    private static void Main(string[] args)
    {
        var sendResult = send(options.FileName, options.Url).Result;
        Console.WriteLine(sendResult);
    }
    

    注意 - 这只能在控制台应用程序中使用。由于同步上下文封送处理,使用Task.WaitTask.Result 将导致其他应用程序类型(不是控制台)中的死锁。

    【讨论】:

    • 这就是解决方案。谢谢!我发现我必须对异步在不同类型的应用程序上的确切工作方式做足功课
    猜你喜欢
    • 1970-01-01
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多