繁体   English   中英

HttpClient.PostAsJsonAsync引发TaskCanceledException

[英]HttpClient.PostAsJsonAsync throws TaskCanceledException

我正在使用HttpClient.PostAsJsonAsync,并且POST从不发送。 我正在用wireshark监视它,什么都没发生。

我觉得这里有些僵局,但不知道是什么。 我已阅读并遵循了指南,但仍然没有。 我已经尝试过ConfigureAwait(false),async,await,都为async方法创建了一个新任务,但是该调用从未返回,也从未发布过该帖子。

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();
        }
}

这是一个与网络有关的问题。 选择了一个wifi USB板,问题得以解决。 仍然不知道是什么阻止了这些请求...因为有了邮递员,一切正常,但是在Visual Studio中却没有...但是代码还可以。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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