简体   繁体   中英

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

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:

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). I've checked this behavior with with Fiddler and it works fine as far as the server is concerned.

Unfortunately the execution finish right after calling PutAsync method.

What I do wrong?

You're executing this from a console application, which will terminate after your call to send . You'll have to use Wait or Result on it in order for Main not to terminate:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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