WebClient UploadStringTaskAsync失败,没有异常

时间:2015-11-18 17:29:40

标签: c# async-await webclient

我在我编写的一个宁静的Web API 2 post方法上调用UploadStringTaskAsync,它没有例外。如果我将调用更改为UploadString,它将按预期工作。我尝试了很多不同的方法。使用UploadStringTaskAsync尝试Fiddler确实显示正在发布的帖子,但内容长度不匹配(见下文)。我正在从测试控制台应用程序中包含的类库中运行此调用。 .Net 4.5.2到目前为止,只是从VS 2015运行调试模式。这是我的代码:

private async Task PostLoggingItem(SmgLoggingItem loggingItem)
    {
        try
        {
            //using (WebClient client = new WebClient())
            //{
            //WebClient client = new WebClient();

                const string authToken = "mytoken";

                loggingItem.AuthToken = Encryptor.GenerateSecurityToken(authToken);

                client.Encoding = Encoding.UTF8;

                //client.Credentials = CredentialCache.DefaultNetworkCredentials;
                //client.UseDefaultCredentials = true;
                client.Credentials = new NetworkCredential("user","mypwd","mydom");

                // set content type to JSon
                client.Headers.Add("Content-Type", "application/json");

                var jsonItem = JsonConvert.SerializeObject(loggingItem);
            var response = await client.UploadStringTaskAsync(new Uri(ConfigurationManager.AppSettings["WebLogAPI"]), jsonItem);

            //string response = client.UploadString(new Uri(ConfigurationManager.AppSettings["SMGWebLogAPI"]), "POST", jsonItem);

            string result = JsonConvert.DeserializeObject<string>(response);

                if (result != "ok")
                {
                    await SMTPSendEmailAsync.SendEmail("brownp@spectrummg.com", "logging failed WebAPI call",
                        "Error return from WebAPI call in PostLoggingItem");
                }
                return;

            //}
        }
        catch (Exception e)
        {
            await SMTPSendEmailAsync.SendEmail("brownp@spectrummg.com", "logging failed WebAPI call",
                "Exception in PostLoggingItem" + e.Message);
            return;
        }
    }

你可以看到我已经注释掉了工作的UploadString调用。另外,我有一个与WebClient对象的“生命周期”相关的理论问题,因此在方法中创建它(参见注释使用),但现在使用PostLoggingItem所属的对象实例化创建它。

这里是小提琴手: enter image description here

我肯定想知道为什么Async不起作用。此外,我使用了异步方法并等待调用树的所有方式 - 无济于事。

0 个答案:

没有答案