gpt4 book ai didi

C# HttpClient 跟踪卡住

转载 作者:行者123 更新时间:2023-11-30 17:36:12 24 4
gpt4 key购买 nike

我想记录我的请求/响应,但我遇到了问题。我的请求卡在了某个点,我不知道为什么。

在我的 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 时,您混合了同步和异步调用。

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com