Search code examples
c#httpclientxmlserializer

Is it possible to read results of the XmlSerializer being sent by HTTPClient?


I am using an extension method to post xml using the HTTPClient which works great.

My question: Is it possible to read, log, or display the results of the XmlSerializer data that is being sent/posted ?

    public static class HttpExtensions  {
    public static Task<HttpResponseMessage> PostAsXmlWithSerializerAsync<T>(this HttpClient client, string requestUri, T value)
    {
        return client.PostAsync(requestUri
                                , value
                                , new XmlMediaTypeFormatter { UseXmlSerializer = true }
                                );
    }
}

Solution

  • PostAsync hides the actually sent HttpRequestMessage from you, though you can retrieve it from the response, too so you can trace both the request and response contents:

    var response = await client.PostAsync(uri, value, formatter);
    Log(response);
    

    If you really want to log the request only, create the request manually:

    var request = new HttpRequestMessage(HttpMethod.Post, uri);
    request.Content = new StreamContent(myXmlStream);
    Log(request);
    var response = await client.SendAsync(request);
    Log(response);
    

    And now you can create one or two Log overloads. I show it for the response, which includes both the request and response log. This is independent from the format, works for both XML and json content.

    protected virtual void Log(HttpResponseMessage response)
    {
        // Use any log/trace engine here, this example uses Debug
        Debug.WriteLine($"Response of the API Call [{response.RequestMessage.Method}] {response.RequestMessage.RequestUri}: {response.StatusCode} {FormatResponse(response)}");
    }
    
    private static string FormatResponse(HttpResponseMessage response)
    {
        var result = new StringBuilder();
        result.AppendLine();
        result.AppendLine("Original request:");
        result.AppendLine(FormatHttpMessage(response.RequestMessage.Headers, response.RequestMessage.Content));
        result.AppendLine();
        result.AppendLine("Obtained response:");
        result.AppendLine(FormatHttpMessage(response.Headers, response.Content));
    }
    
    private static string FormatHttpMessage(HttpHeaders headers, HttpContent content)
    {
        var result = new StringBuilder();
        var headersString = headers.ToString();
        if (!string.IsNullOrWhiteSpace(headersString))
        {
            result.AppendLine("Headers:");
            result.AppendLine(headersString);
            result.AppendLine();
        }
    
        if (content != null)
        {
            result.AppendLine("Content:");
            result.AppendLine(content.ReadAsStringAsync().Result);
        }
    
        return result.ToString();
    }