来自Xamarin应用程序的第二次api调用失败(第一次调用总是返回ok)

时间:2016-07-06 07:16:29

标签: c# sockets xamarin mono xamarin.android

我有一个web api,由xamarin应用程序使用。 每当我第一次执行web api调用时,它都会成功。但是,每次连续呼叫都会失败:

xamarin应用示例:

[Activity(Label = "App1", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        int count = 1;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.MyButton);

            button.Click += async delegate
            {
                var cl = new HttpClient();

                cl.BaseAddress = new Uri("http://10.0.5.220/api/");

                var request = new HttpRequestMessage(HttpMethod.Get, "values");
                HttpResponseMessage res = null;
                button.Text = "";
                try
                {
                    res = await cl.SendAsync(request);
                    var stream = await res.Content.ReadAsStreamAsync();

                    StreamReader sr = new StreamReader(stream);

                    button.Text = await sr.ReadToEndAsync();
                }
                catch (Exception ex)
                {

                }
            };
        }
    }

第一次调用正确返回“value1”和“value2”

第二次调用,当我再次单击该按钮时(以及之后的任何按钮):

  

{System.Net.WebException:错误:ConnectFailure(无主机路由)   ---&GT; System.Net.Sockets.SocketException:没有到System.Net.Sockets.Socket.Connect(System.Net.EndPoint remoteEP)的主机路由   [0x000cb] in   /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/System/System.Net.Sockets/Socket.cs:1313   在System.Net.WebConnection.Connect(System.Net.HttpWebRequest   请求)[0x0019b] in   /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/System/System.Net/WebConnection.cs:195   ---内部异常堆栈跟踪结束---在System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)   [0x0005e] in   /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:1005   在System.Threading.Tasks.TaskFactory 1[TResult].FromAsyncCoreLogic (IAsyncResult iar, System.Func 2 endFunction,System.Action 1 endAction, System.Threading.Tasks.Task 1 promise,Boolean   requiresSynchronization)[0x00014] in   /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/threading/Tasks/FutureFactory.cs:550

然而,这只发生在Android应用程序中,iOS应用程序正常工作。

控制器中的断点永远不会被击中。似乎请求在到达控制器之前被取消了?

1 个答案:

答案 0 :(得分:0)

由于我真的不熟悉HTTP请求,流及其所暗示的内容,我的回答可能与问题完全无关。如果是这样,请在评论或编辑中纠正我。

您获得响应的方式让StreamReader打开,但情况并非如此。请改用:

using(StreamReader sr = new StreamReader(stream)) {
    button.Text = await sr.ReadToEndAsync();
}

这将允许StreamReader在操作完成后关闭。