asp.net web api - .NET Web Api Logging Response Body -


I'm trying to use DelegatingHandler these Web APIs react physically connected.

  Protected override System.Threading.Tasks.Task & LT; HttpResponseMessage & gt; SendAsync (HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) {return base.SendAsync (request, cancellationToken) .ContinueWith (Work = & gt; {var response = task.Result; LogResponseLoggingInfo (response); return response;}); } Private Zero LogResponseLoggingInfo (HttpResponseMessage response) {string responseBody = string.Empty; If (response.Content = null!) {ResponseBody = response.Content.ReadAsStringAsync () results. // WriteToLogFile (responseBody); }}  

This works fine as long as the call as Web API returns to the equals a response.StatusCode HttpStatusCode.OK work.

But are any calls that another StatusCode returns, unauthorized, for example, the correct response results in 401 being only back properly on each call

The second time, I receive 500 responses, an internal server error

An HTML document by using Fiddler to see the raw response for 500 errors shows that the server HTTP header has been sent After the message And can not be attached.

If I responseBody = response.Content.ReadAsStringAsync () Results result comment , correct 401 error response has returned successfully every time.

Does anyone know what the error is causing and how to fix it?

Try to change the handler to use instead async / await:

  Protected Override async works & lt; HttpResponseMessage & gt; To SendAsync (HttpRequestMessage request, cancel System.Threading.CancellationToken token) support {var response = base. SendAsync (request, cancellation token); Awaiting LogResponsion logging info (feedback); Return feedback; } Task LogResponseLoggingInfo (HttpResponseMessage response) async personal {string responseBody = string.Empty; If (response.Content! = Null) {responseBody = Waiting for feedback. Content RedAssressingSync (); // WriteToLogFile (responseBody); }}  

Continue with and. If you use ASC / wait, you will not need it. Here's some more information: and


Comments