I want to log my request/response but I'm having a problem. My request stuck at some point which I have no idea why.
Inside my controller I've this code
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);
}
}
and my 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();
}
}
My debug stuck at:
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
Can someone please put some light and explain me why it's stuck?
Appreciate any help :)
You are mixing synchronous and asynchronous call when you use .Result.
HttpResponseMessage response = client.PostAsync("api/UserDetails/Register", content).Result;
That is what is causing deadlock.
Either go async all the way or not at all.
var response = await client.PostAsync("api/UserDetails/Register", content);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With