1

.NET Core 2

The client just dies instantly when it tries to send a get request to server. If I use Postman then it works fine, but I need to do it via C#. This is the piece of my code which is for getting files from server:

var client = new HttpClient();
client.Timeout = TimeSpan.FromMinutes(timeSpanFromMinutes);

try
{
    // At this code row the application shutdown without any exception. 
    // Even doesn't work the 'catch' block of try\catch...
    HttpResponseMessage response = await client.GetAsync(url + "/Home/Download/" + args[1], 
        HttpCompletionOption.ResponseContentRead);
    // I will not be here    
    Console.WriteLine("Response status code: {0}", response.StatusCode);
    if (response.StatusCode == HttpStatusCode.OK)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            await response.Content.CopyToAsync(ms);
            Console.WriteLine("Data successfully recieved from server. Data length: {0}",
                ms.Length);

            string resultFileName = Path.Combine(resultFolder, new Guid().ToString()
                                                     + resultFileExtension);
            using (FileStream fs = new FileStream(resultFileName, FileMode.Create))
            {
                fs.Read(ms.GetBuffer(), 0, (int) ms.Length);
            }

            Console.WriteLine("The result was saved in the '{0}' file.", resultFileName);
        }
    }
}
catch (Exception ex)
{   // I will not be here
    Console.WriteLine("Exception: {0}", ex.Message);
}

Server is launched and accessible. All variables are initialized and content the valid values. The post request works without problem. I have the problem for get request. I commented the problem code row.

What can be the reason of such behaviour?

UPD

This is full code of my client side (the problem is for "get" command):

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
           var task = Task.Run(()=>{
                Work(args);
           });
           task.Wait();
        }

        static async Task Work(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Application invalid parameters.");
                WriteHelp();
                return;
            }

            string xmlFileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                "Client.settings.xml");

            XElement xml = XElement.Load(xmlFileName);

            string url = xml.Element("url").Value?.Trim()?.TrimEnd('/');
            string resultFolder = Environment.ExpandEnvironmentVariables(xml.Element("resultsFolder").Value);

            if (!Directory.Exists(resultFolder))
            {
                Directory.CreateDirectory(resultFolder);
            }

            string resultFileExtension = Environment.ExpandEnvironmentVariables(xml.Element("resultFileExtension").Value);
            int timeSpanFromMinutes = Int32.Parse(xml.Element("TimeSpanFromMinutes").Value);

            switch (args[0])
            {
                // Send data to server
                case "post":
                {
                    string fileName = Environment.ExpandEnvironmentVariables(args[1]);

                    if (!File.Exists(fileName))
                    {
                        Console.WriteLine("File '{0}' not found.", fileName);
                        return;
                    }
                    else
                    {
                        var client = new HttpClient();
                        client.Timeout = TimeSpan.FromMinutes(timeSpanFromMinutes);

                        try
                        {
                            using (FileStream fs = new FileStream(fileName, FileMode.Open))
                            {
                                HttpResponseMessage response = await client.PostAsync(url + "/Home/Upload", 
                                    new StreamContent(fs));

                                Console.WriteLine("Response status code: {0}", response.StatusCode);
                                if (response.StatusCode == HttpStatusCode.OK)
                                {
                                    // The task ID. It is to be used for get the data handling result from server later.
                                    string id = await response.Content.ReadAsStringAsync();
                                    Console.WriteLine("Task ID: {0}", id);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Exception: {0}", ex.Message);
                        }
                    }

                    break;
                }
                // get the result of data handling from server
                case "get":
                {
                    Guid guid = Guid.Empty;

                    if (!Guid.TryParse(args[1], out guid))
                    {
                        Console.WriteLine("Invalid identifier (GUID): '{0}'", args[1]);
                        return;
                    }

                    var client = new HttpClient();
                    client.Timeout = TimeSpan.FromMinutes(timeSpanFromMinutes);

                        try
                        {
                            // TODO: the problem is here
                            var response = await client.GetAsync(url + "/Home/Download/" + args[1], 
                                HttpCompletionOption.ResponseContentRead);

                            Console.WriteLine("Response status code: {0}", response.StatusCode);
                            if (response.StatusCode == HttpStatusCode.OK)
                            {
                                using (MemoryStream ms = new MemoryStream())
                                {
                                    await response.Content.CopyToAsync(ms);
                                    Console.WriteLine("Data successfully recieved from server. Data length: {0}",
                                        ms.Length);

                                    string resultFileName = Path.Combine(resultFolder, new Guid().ToString()
                                                                             + resultFileExtension);
                                    using (FileStream fs = new FileStream(resultFileName, FileMode.Create))
                                    {
                                        fs.Read(ms.GetBuffer(), 0, (int) ms.Length);
                                    }

                                    Console.WriteLine("The result was saved in the '{0}' file.", resultFileName);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Exception: {0}", ex.Message);
                        }

                    break;
                }
                default:
                {
                    Console.WriteLine("Unknown command: {0}", args[0]);
                    WriteHelp();
                    return;
                }
            } 
        }

        private static void WriteHelp()
        {
            string text =
@"
Client.dll
(c) Andrey Bushman, 2018

This client allows to send data to server and get the results of their handling.

The application using format:

    dotnet Client.dll <command> <parameter>

## COMMAND

    post - send file to server. The request contains status code and GUID for getting the data handling result later.

    get - get data handling result by GUID. If result doesn't exist still then recuest code is 'File not found'. 

## PARAMETER

    It is the file full name for the 'post' command or the GUID for the 'get' command.

## EXAMPLES

Upload the file to server:

    dotnet Client.dll post /home/andrey/tmp/data.foo

Download the data handling result from server by GUID:

    dotnet Client.dll get 3d600895-f11c-4fa0-865e-411d52daf469";

            Console.WriteLine(text);
        }
    }
}

Full code sources are here on GitHub.

H H
  • 263,252
  • 30
  • 330
  • 514
Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182

1 Answers1

3

Pay attention to the compiler warnings:

 var task = Task.Run(()=>{
     Work(args);
 });
 task.Wait();

It should tell you that Work(args) is not being awaited here. That means that any excption it throws will be unobserved.

Since we are in a Console app, Task.Run() has no real purpose.
Use the following instead:

static void Main(string[] args)
{
    try
    {
        var task = Work(args);
        task.Wait();
    }
    catch (Exception ex)
    {
       // log or put a breakpoint here        
    }
}
H H
  • 263,252
  • 30
  • 330
  • 514
  • 1
    If this is C# 7.1, we can also do `static async Task Main` and await the task. – mason Mar 30 '18 at 15:19
  • Yes, but would that improve anything? – H H Mar 30 '18 at 15:22
  • Of course - you should avoid calling `.Wait()`. You should await tasks instead. That's kind of the whole point of making it so that apps can have an async main method. – mason Mar 30 '18 at 15:29
  • Avoid `.Wait()` in anything but a Console app. It don't think it matters here. Use whatever you want, but put a try/catch around it. – H H Mar 30 '18 at 15:44
  • Also see [this](https://stackoverflow.com/q/46219114/60761) and [this](https://blogs.msdn.microsoft.com/mazhou/2017/05/30/c-7-series-part-2-async-main/) : "just syntactic sugar" – H H Mar 30 '18 at 15:49