Xamarin表单Visual Studio 2015 HttpClient请求不在iOS上运行

我对Xamarin Forms / Visual Studio很新,但这是我目前的情况。 我在Visual Studio中有一个带有Android,iOS和Windows Phone子项目的Xamarin Forms项目。 我有以下function登录:

public async Task<Tuple> Login(LoginCredentials credentials) { var loginUrl = apiUrl + "/login"; var json = JsonConvert.SerializeObject(credentials); var content = new StringContent(json, Encoding.UTF8, "application/json"); try { Debug.WriteLine("start of try block"); HttpResponseMessage response = await client.PostAsync(loginUrl, content); Debug.WriteLine("this will not print on iOS"); string bodyStr = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { // code that does stuff with successful response } else { // code that does stuff with bad response } } catch (Exception e) { Debug.WriteLine(e); return new Tuple(false, e.Message); } } 

正如您在Debug.WriteLine()看到的那样,在该行上抛出exception:

 HttpResponseMessage response = await client.PostAsync(loginUrl, content); 

System.NullReferenceException: Object reference not set to an instance of an objectexceptionSystem.NullReferenceException: Object reference not set to an instance of an object

但是,此exception仅发生在iOS上。 Android和Windows Phone都可以成功发出此请求。

我的第一个假设是Apple的ATS是有意义的,因为我的服务器只是一个不使用https的开发实例。 所以我粘贴了

 NSAppTransportSecurity  NSAllowsArbitraryLoads   

到iOS项目的Info.plist。 仍然没有运气。

我还在其他地方读过一个问题,要求确保Windows上的Visual Studio和Mac上的Xamarin都是最新的,我也确定了这一点。

另外apiUrl不是http://localhost我在本地网络上使用IP(因为Mac和iOS模拟器在不同的机器上运行)我已经确认是正确的。

如果我不得不在这一点上猜测,我会说它仍然是ATS设置没有正确设置但我无法确认这一点。 不知道从哪里开始。 我将继续调试并添加更新,但任何帮助将非常感谢。

更新:

正如Oleg Bogdanov所建议的那样,我的客户端实例只有在运行iOS时才能正确实例化。

调试iOS时: iOS HttpClient调试

调试Android时: Android HttpClient Debug

现在,任务变得弄清楚为什么在iOS上发生这种情况。 这是client初始化代码。 我已经尝试了它当前的位置和评论的位置。

 public class API { public HttpClient client = new HttpClient(); public string apiUrl = "http://myApiUrl"; public API() { //this.client = new HttpClient(); } public async Task<Tuple> Login(LoginCredentials credentials) { // login function code } } 

当我有任何新的发展时,我会继续调试这个并发布另一个更新。 像往常一样,任何帮助都非常感激。

我在这里找到了解决方案。

我运行NuGet Install-Package Microsoft.Net.Http到Portable项目,它现在正在运行。

我不认为有任何ATS。 我使用localhost共享本地服务器创建了一个POC。 请检查以下适用于我的POC的代码

对于POST请求

 try { HttpClient client = new HttpClient(); var uri = new Uri("http://localhost/RegisterDevice"); string data = "{\"username\": \"ADMIN\",\"password\": \"123\"}"; var content = new StringContent(data, Encoding.UTF8, "application/json"); HttpResponseMessage response = null; response = await client.PostAsync(uri, content); Util.HideLoading(); if (response.IsSuccessStatusCode) { System.Diagnostics.Debug.WriteLine(@"Success"); } else { System.Diagnostics.Debug.WriteLine(@"Fail"); } } catch (Exception ex) { }