是否可以读取HTTPClient发送的XmlSerializer的结果?

时间:2017-06-08 04:23:28

标签: c# httpclient xmlserializer

我使用扩展方法使用HTTPClient发布xml,效果很好。

我的问题:是否可以读取,记录或显示正在发送/发布的XmlSerializer数据的结果?

    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 }
                                );
    }
}

2 个答案:

答案 0 :(得分:0)

是的,你可以。 下载并安装Fiddler,然后过滤您的requestUri,您可以监控所有传输的数据,例如您序列化的xml。

答案 1 :(得分:0)

PostAsync会隐藏实际发送的HttpRequestMessage,但您也可以从响应中检索它,以便您可以跟踪请求和响应内容:

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

如果您确实只想记录请求,请手动创建请求:

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

现在您可以创建一个或两个Log重载。我为响应显示它,包括请求和响应日志。这与格式无关,适用于XML和json内容。

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();
}