HttpClient的行为不符合预期

时间:2018-07-29 12:38:11

标签: c# task console-application

我的C#应用​​程序将文件上传到某个API,我正在使用多部分请求,即,我正在上传文件的json字符串和二进制连接,它适用于大多数文件,但是很少执行任何操作,我意味着让我们尝试名为file.pdf的文件:

我的代码大致如下:

public async Task<Dictionary<string , string>> Upload(string filePath)
{   
      FileInfo fi = new FileInfo(FilePath);

      string jsonString="some json string";

      byte[] fileContents=File.ReadAllBytes(fi.FullName);

      Uri webService = new Uri(url);

      HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post , webService);

      requestMessage.Method = HttpMethod.Post;

      requestMessage.Headers.Add("Authorization" , "MyKey1234");

      const string boundry = "------------------My-Boundary";

      MultipartFormDataContent multiPartContent = new MultipartFormDataContent(boundry);

      ByteArrayContent byteArrayContent = new ByteArrayContent(fileContents);

      multiPartContent.Add(byteArrayContent);

      requestMessage.Content = multiPartContent;

      HttpClient httpClient = new HttpClient();

      Console.WriteLine("before");

HttpResponseMessage httpResponse = await httpClient.SendAsync(requestMessage , HttpCompletionOption.ResponseContentRead , CancellationToken.None);

Console.WriteLine("after");
    }

呼叫者:

myDictionary = await Upload(filePath);

输出:

before
Press any key to continue . . .

我的意思是没有例外,没什么,这是什么?一个错误?

修改

控制台应用程序的结构如下:

class Program
{
    static void Main(string[] args)
    {
        new MyClass().Start();
    }
}

MyClass:

public async void Start()
{
  myDictionary = await Upload(filePath);
}

1 个答案:

答案 0 :(得分:3)

如评论部分所述,您的main方法不会等待可等待的调用,也不会等待HttpClient实例来处理响应。

如果控制台应用程序用于测试,则可以在方法返回的任务实例上调用.Result属性,如下所示:

new MyClass().Start().Result;

但是,最好像这样使用async关键字on the main method that has been made available in C# 7.1

class Program
{
   static async Task Main(string[] args)
   {
        await new MyClass().Start();
   }
}

最后,作为recommended,您应将后缀'Async'添加到异步方法名称中。例如,Start将被命名为StartAsync