我想记录我的请求/响应,但我遇到了问题。
我的请求停留在某个时间点,我不知道为什么。
在我的 Controller 里面我有这个代码
var log = new LoggingHandler();
using (var client = new HttpClient(log))// <-- problem here
{
string baseUrl = ConfigurationManager.AppSettings["apiBaseAddress"];
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
foreach (var website in websitesList)
{
string stringtime = TimeHandler.GetCurrentDateTime();
var userModel = new RegisterModel()
{
// my user model
};
var content = new FormUrlEncodedContent(new[]
{
//encoding model
});
try
{
HttpResponseMessage response = client.PostAsync("api/UserDetails/Register", content).Result;
//tResult.URL = response.RequestMessage.RequestUri.OriginalString;
tResult.URL = website.URL;
tResult.Result = response.ReasonPhrase;
var statusCode = response.StatusCode.ToString();
.
.
.
.
}
tResult.TestLog = log.GetLog();//*****
resultList.Add(tResult);
}
}
和我的 LoggingHandler
public class LoggingHandler : DelegatingHandler
{
StringBuilder sb = new StringBuilder();
public LoggingHandler()
: base(new HttpClientHandler())
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
sb.AppendLine("Request:");
sb.AppendLine(request.ToString());
if (request.Content != null)
{
sb.AppendLine(await request.Content.ReadAsStringAsync());
}
sb.AppendLine();
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
sb.AppendLine("Response:");
sb.AppendLine(response.ToString());
if (response.Content != null)
{
sb.AppendLine(await response.Content.ReadAsStringAsync());
}
sb.AppendLine();
return response;
}
public string GetLog()
{
return sb.ToString();
}
}
我的调试停留在:
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
有人可以请说明一下并解释为什么它被卡住了吗?
感谢任何帮助:)
最佳答案
当您使用 .Result
时,您正在混契约(Contract)步和异步调用。
HttpResponseMessage response = client.PostAsync("api/UserDetails/Register", content).Result;
这就是导致死锁的原因。
要么一直异步,要么根本不异步。
var response = await client.PostAsync("api/UserDetails/Register", content);
关于C# HttpClient 跟踪卡住,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40015528/