I created a message handler that will log the request and response. ideally i want
public class LoggingMessageHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { LogRequest(request); return base.SendAsync(request, cancellationToken).ContinueWith(task => { var response = task.Result; LogResponse(response); return response; }); } private void LogRequest(HttpRequestMessage request) { var writer = request.GetConfiguration().Services.GetTraceWriter(); var content = request.Content; (content ?? new StringContent("")).ReadAsStringAsync().ContinueWith(x => { writer.Trace(request, "request", System.Web.Http.Tracing.TraceLevel.Info, t => { t.Message = x.Result; }); }); } private void LogResponse(HttpResponseMessage response) { var request = response.RequestMessage; var writer = request.GetConfiguration().Services.GetTraceWriter(); var content = response.Content; (content ?? new StringContent("")).ReadAsStringAsync().ContinueWith(x => { writer.Trace(request, "response", System.Web.Http.Tracing.TraceLevel.Info, t => { t.Status = response.StatusCode; t.Message = x.Result; }); }); } }
and here is my client code.
public ActionResult Index() { var profile = Client.GetAsync("Vendor").Result.EnsureSuccessStatusCode().Content.ReadAsAsync<VendorProfileModel>().Result; return View(profile); }
The work of the magazine works. However, when this handler is registered, my client code returns an empty object. If I remove this handler, the model will be successfully read from the response and displayed on the screen.
Is there a way to read the content and display the results on the client?
asp.net-web-api
Jason meckley
source share