HttpClient.PostAsJsonAsync抛出TaskCanceledException

时间:2017-08-18 15:03:50

标签: c# asynchronous

我使用HttpClient.PostAsJsonAsync并且永远不会发送POST。我用wireshark监视它,没有任何东西出来。

我觉得这里有些东西陷入僵局,但无法弄清楚是什么。我已经阅读了this指南并关注了它,但仍然没有。我已经尝试过ConfigureAwait(false),async,await,为异步方法创建一个新任务,但是永远不会返回该调用,并且永远不会发布该帖子。

public class RequestDespacho
    { 
    /* 
         several public properties
    */
    public async void MakeRequest()
            {
                try
                {                        
                var response = await Requester.MakePost("CreateTicket/", this);
                    switch (response.StatusCode) //this line is never reached
                    {
                        case HttpStatusCode.OK:
                            MessageBox.Show("OK");
                            break;
                        case HttpStatusCode.Forbidden:
                            MessageBox.Show("Forbidden");
                            break;
                        case HttpStatusCode.BadRequest:
                            MessageBox.Show("Bad Request");
                            break;
                        case HttpStatusCode.InternalServerError:
                            MessageBox.Show("Internal Server Error");
                            break;
                    }

                }
                catch (Exception e) //taskCanceled exception appears after a while
                {
                    MessageBox.Show(e.ToString());
                }

            }
    }
public static class Requester
    {
        private static readonly HttpClient client;

        static Requester()
        {
            client = new HttpClient()
            {
                BaseAddress = new Uri("http://10.2.4.29:1234/"),
                DefaultRequestHeaders = {{"x-auth_token", "token1"}},
                Timeout = new TimeSpan(0, 0, 15)
            };
        }
        public static async Task<HttpResponseMessage> MakePost(string dir, object data)
        {
            return await client.PostAsJsonAsync(dir, data);
        }
    }
public partial class Form1 : Form
{
    private async void button3_Click(object sender, EventArgs e)
        {
            var image = File.ReadAllBytes(@"G:\1.jpg");
            RequestDespacho req = new RequestDespacho("Av. Monroe 2323", -34.557762, -58.459346, TipoEvento.Merodeo,
                "Palio rojo", image); //my model, doesn't really matter
            await req.MakeRequest();
        }
}

1 个答案:

答案 0 :(得分:0)

这是与网络相关的问题。连接wifi usb板,问题解决了。仍然不知道是什么阻止了请求...因为邮差一切都有效,但在视觉工作室它没有...但代码是好的。