[英]Are iOS, Android, Windows 10 mobile emulators available for developing Xamarin.Forms with Visual Studio 2015?
[英]Xamarin Forms Visual Studio 2015 HttpClient requests not working on iOS
我对 Xamarin Forms/Visual Studio 比较陌生,但这是我目前的情况。 我在 Visual Studio 中有一个 Xamarin Forms 项目,其中包含 Android、iOS 和 Windows Phone 子项目。 我有以下功能登录:
public async Task<Tuple<bool, object>> 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<bool, object>(false, e.Message);
}
}
从Debug.WriteLine()
可以看出,该行抛出异常:
HttpResponseMessage response = await client.PostAsync(loginUrl, content);
例外是System.NullReferenceException: Object reference not set to an instance of an object
但是,此异常仅发生在 iOS 上。 Android 和 Windows Phone 都可以成功发出此请求。
我的第一个假设是它是Apple 的 ATS ,这很有意义,因为我的服务器只是一个不使用 https 的开发实例。 所以我粘贴了
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
到 iOS 项目的 Info.plist。 仍然没有运气。
我还在别处读到了一个问题,说要确保 Windows 上的 Visual Studio 和 Mac 上的 Xamarin 都是最新的,我也确保了这一点。
另外apiUrl
不是http://localhost
我在我的本地网络上使用 IP(因为 Mac 和 iOS 模拟器在不同的机器上运行),我已经确认这是正确的。
如果我不得不在这一点上猜测,我会说它仍然是 ATS 设置未正确设置的问题,但我一直无法确认这一点。 不知道从这里去哪里。 我将继续调试和添加更新,但任何帮助将不胜感激。
正如Oleg Bogdanov所建议的,只有在运行 iOS 时,我的客户端实例才能正确实例化。
现在的任务是弄清楚为什么在 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<bool, object>> 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)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.