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

本文关键字:调用 第一次 返回 ok 失败 应用程序 Xamarin 第二次 api 来自 | 更新日期: 2023-09-27 17:55:38

我有一个由xamarin应用程序使用的Web api。每当我第一次执行 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)
                {
                }
            };
        }
    }

第一次调用正确返回"值 1"和"值 2"

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

{System.Net.WebException: Error: ConnectFailure (没有到主机的路由) ---> System.Net.Sockets.SocketException:没有路由到主机在System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x000cb] 在 /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/System/System.Net.Sockets/Socket.cs:1313 at System.Net.WebConnection.Connect (System.Net.HttpWebRequest 请求) [0x0019b] 在 /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/System/System.Net/WebConnection.cs:195 --- 内部异常堆栈跟踪结束 --- at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x0005e] 在 /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:1005 at 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

但是,这只发生在安卓应用程序中,iOS应用程序工作正常。

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

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

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

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

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

这将允许流读取器在操作完成后关闭。