简体   繁体   English

HttpClient.PutAsync立即完成,没有响应

[英]HttpClient.PutAsync finish immediately with no response

I try to upload a file with PUT method to the http server (Apache Tika) with the following code 我尝试使用以下代码将具有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();
    }
}

In Main the method is called this way: 在Main中,此方法称为:

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

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

In response the server should return HTTP 200 and text response (parsed pdf file). 作为响应,服务器应返回HTTP 200和文本响应(已解析的pdf文件)。 I've checked this behavior with with Fiddler and it works fine as far as the server is concerned. 我已经使用Fiddler检查了此行为,并且就服务器而言,它工作正常。

Unfortunately the execution finish right after calling PutAsync method. 不幸的是,调用PutAsync方法后执行立即完成。

What I do wrong? 我做错了什么?

You're executing this from a console application, which will terminate after your call to send . 您正在从控制台应用程序执行此操作,该控制台应用程序将在您调用send之后终止。 You'll have to use Wait or Result on it in order for Main not to terminate: 您必须在上面使用WaitResult ,以便Main不会终止:

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

Note - this should be only used inside a console application . 注意– 仅应在控制台应用程序内使用 Using Task.Wait or Task.Result will result in a deadlock in other application types (which are not console) due to synchronization context marshaling. 由于同步上下文封送处理,使用Task.WaitTask.Result将导致其他应用程序类型(不是控制台)中的死锁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM