![](/img/trans.png)
[英]C# HttpClient - PostAsync doesn't return (even with ConfigureAwait)
[英]C# HttpClient.PostAsync doesn't return or throw an error
我有一個 Windows 服務發出 HTTP POST 請求。 REST 端點正在工作,並且已單獨測試。 調用PostAsync
后,調試器不會繼續或拋出錯誤。 導致這種行為的可能問題是什么? 以下是發送 POST 請求的代碼片段,
編輯:我已將其更改為 async-await 並使用了ConfigureAWait
,但這並沒有解決問題。 我需要知道是什么導致 function 不返回任何值。
HttpClientHandler handler = GetCookieHandler();
using(HttpClient client = new HttpClient(handler)) {
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("basic", accessToken);
client.DefaultRequestHeaders.Add("UniqueId", _configReader.UniqueId);
SetRequestCookie(handler);
string jsonContent = JsonConvert.SerializeObject(content);
HttpResponseMessage response = client.PostAsync(url, new StringContent(jsonContent, Encoding.UTF8, "application/json")).Result;
SaveCookie(handler, response.RequestMessage.RequestUri);
if (response.StatusCode == HttpStatusCode.Unauthorized) {
var customerJsonString = response.Content.ReadAsStringAsync().Result;
Error data = JsonConvert.DeserializeObject < Error > (customerJsonString);
switch (data.ErrorCode) {
case AccessTokenValidationCodes.ExpiredOrInvalidDateTime:
logger.Warn("Expired AccessToken");
break;
default:
break;
}
}
if (response.StatusCode == HttpStatusCode.Unauthorized) {
logger.Error("Request :{0}, AccessToken {1} response Unauthorized", apirUrl, accessToken);
return null;
}
if (response.StatusCode == HttpStatusCode.InternalServerError) {
logger.Warn("Request response InternalServerError");
return null;
}
return response;
}
除了我的重復評論,您需要閱讀最后的回復。 目前,您僅在未經授權的情況下執行此操作,但無論如何您都應該閱讀以結束。 確保您從評論中獲得建議,包括關於異步等待的建議,以及:
將 ReadAsString 線移出並確保它對端點的所有調用都運行。
HttpResponseMessage response = client.PostAsync(url, new StringContent(jsonContent, Encoding.UTF8, "application/json")).Result;
var customerJsonString = response.Content.ReadAsStringAsync().Result;
你的代碼
if (response.StatusCode == HttpStatusCode.Unauthorized) {
var customerJsonString = response.Content.ReadAsStringAsync().Result;
Error data = JsonConvert.DeserializeObject < Error > (customerJsonString);
switch (data.ErrorCode) {
case AccessTokenValidationCodes.ExpiredOrInvalidDateTime:
logger.Warn("Expired AccessToken");
break;
default:
break;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.