Httpmessagehandler - reading content

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?

+1
asp.net-web-api
source share
1 answer

after a few days to search the net, I finally found a root problem and solution. First problem:

  • everything in webapi isync
  • My action uses Controller.User, which in turn calls Thread.CurrentPrinciple
  • I use ITraceWriter as my registration abstraction

Obviously, there is an error in the ITraceWriter mechanics when the current profile does not propagate over streams. therefore, I lose the principle when I get to my action with the controller. so my query returns an empty result, and not a completely filled result.

solution: do not use ITraceWriter to register messages. It would be nice to use the built-in mechanics, but that won't work. here is a link to the same issue that provides more details / context.

https://aspnetwebstack.codeplex.com/workitem/237

0
source

All Articles