【发布时间】:2021-05-14 12:07:52
【问题描述】:
尝试进行 API 调用(asp.net 核心 Web API)时,我的 Xamarin 应用程序死锁。移动应用程序正在使用 Android 模拟器。我按照微软自己的教程创建了 API 和客户端应用程序。使用 Postman 或直接在我的开发机器的浏览器中调用时,请求会正常运行。
常量类:
public static class Constants
{
public static string BaseAddress =
DeviceInfo.Platform == DevicePlatform.Android
? "https://10.0.2.2:44348"
:"https://localhost:44348";
public static string AppointmentsUrl = $"{BaseAddress}/api/appointments/";
}
处理程序:
public class AppointmentHandler
{
HttpClient client;
JsonSerializerOptions serializerOptions;
private List<Appointment> Appointments { get; set; }
public AppointmentHandler()
{
client = new HttpClient();
serializerOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
}
public async Task<List<Appointment>> GetAppointments()
{
Appointments = new List<Appointment>();
try
{
Uri uri = new Uri(string.Format(Constants.AppointmentsUrl, string.Empty));
// the program deadlocks here
HttpResponseMessage response = await this.client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<List<Appointment>>(content, serializerOptions);
}
}
catch (Exception e)
{
var m = e.Message;
}
return null;
}
}
【问题讨论】:
-
您是否使用模拟器中的浏览器验证了从模拟器到服务 url 的连接?
-
是的,我试过了。它说“错误的请求,无效的主机名”。但是为什么它没有检索到应用程序的状态码呢?
-
一个状态码需要成功连接到服务器,你还没有走那么远
标签: c# xamarin dotnet-httpclient