Lal*_*ala 10 .net c# async-await dotnet-httpclient xamarin.forms
我已经看到了很多关于这个的问题,所有人都指向我使用ConfigureAwait(false),但即使这样做,它仍然没有返回任何响应.当我运行调试器时,代码在PostAsync停止,并且不继续我的代码.我在这里做错了吗?是否与我通过HTTPS调用API有关?
这是代码:
public async static Task<PaymentModel> AddAsync(Card card)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:", "hidden"))));
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var cardJson = JsonConvert.SerializeObject(card);
var postRequest = new StringContent(cardJson, Encoding.UTF8, "application/json");
var request = await client.PostAsync(new Uri("https://sample-3rd-party-api/api/endpoint/here"), postRequest).ConfigureAwait(false);
var content = await request.Content.ReadAsStringAsync().ConfigureAwait(false);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
在回应下面的评论时,代码包含在一个方法AddAsync(卡片卡)中,该方法是通过带有处理程序的按钮单击调用的:
public async void OnExecute(object sender, EventArgs args)
{
//some code here
payment = await PaymentModel.AddAsync(card).ConfigureAwait(false);
}
Run Code Online (Sandbox Code Playgroud)
编辑2:我尝试ping API,但它返回一个请求超时,但当我尝试使用Postman时,它做得很好(API只是一个对所有人开放的沙盒,所以可以分享这个):

编辑3:
我认为问题在于我没有SSL证书来访问API.我有一个连接到相同API的PHP服务器,我必须将SSL_VERIFYPEER设置为false才能访问它(不用担心,我现在添加了一个cacert,所以它再次为true).可以在这里发生同样的问题吗?如果是这样,我该怎么做才能为我的xamarin表单应用程序创建有效的证书
这里最有可能发生的是你的OnExecute方法有一个返回类型,void而不是Task阻止 UI 线程等待它。尝试更改返回类型Task或创建新的 UI 线程来执行此工作。只要 Postman 工作,我就不会担心 ping 超时。许多公共 Web 服务器禁用其 ping 响应。