【发布时间】:2020-06-30 05:06:45
【问题描述】:
我正在创建 http 客户端以使用一些 api。
这是我调用 api 端点的客户端方法。
public async Task<HttpResponseMessage> SendRequestAsync()
{
string adaptiveUri = "https://some-api/api/Authentication/AuthenticateThirdPartyUserAsync";
using (HttpClient httpClient = new HttpClient())
{
var json = JsonConvert.SerializeObject(new { userName = "uname", password = "123", applicantCode = "hello" });
var payload = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage responseMessage = null;
try
{
responseMessage = await httpClient.PostAsync(adaptiveUri, payload);
}
catch (Exception ex)
{
if (responseMessage == null)
{
responseMessage = new HttpResponseMessage();
}
responseMessage.StatusCode = HttpStatusCode.InternalServerError;
responseMessage.ReasonPhrase = string.Format("RestHttpClient.SendRequest failed: {0}", ex);
}
return responseMessage;
}
}
调用方法如下
public async Task<IBaseStatus> Handle(InspectionAddedEvent domainEvent)
{
var tk = await _iAClient.SendRequestAsync();
return something;
}
但await 不会等到 postasync 完成。
但是当我使用
httpClient.PostAsync(adaptiveUri, payload).GetAwaiter().GetResult()
它会等到帖子完成。
有人知道吗?
谢谢。
【问题讨论】:
-
不等到完成是什么意思?你怎么知道它没有完成?
-
请查看minimal reproducible example 发布代码指南和edit 问题以显示重现错误行为的所有必要代码 - 到目前为止,帖子中显示的代码是进行异步调用和没有理由相信它会按照您描述的方式行事。您可能希望完全删除所有异常处理(除非它是您的同步路径进入的地方 - 即无效的 DNS 名称可以使此代码同步失败)
标签: c# async-await xmlhttprequest httpclient httpresponse