HttpClient不能正确序列化XML

时间:2014-08-25 19:46:37

标签: c# .net task-parallel-library async-await dotnet-httpclient

在调用HttpClient的扩展方法PostAsXmlAsync时,它会忽略该类的XmlRootAttribute。这种行为是个错误吗?

测试

[Serializable]
[XmlRoot("record")]
class Account 
{
    [XmlElement("account-id")]
    public int ID { get; set }
}


var client = new HttpClient();
await client.PostAsXmlAsync(url, new Account())

1 个答案:

答案 0 :(得分:12)

查看source code of PostAsXmlAsync,我们可以看到它使用XmlMediaTypeFormatter,内部使用DataContractSerializer XmlSerializer。前者不尊重XmlRootAttribute

public static Task<HttpResponseMessage> PostAsXmlAsync<T>(this HttpClient client, Uri requestUri, T value, CancellationToken cancellationToken)
{
      return client.PostAsync(requestUri, value, new XmlMediaTypeFormatter(),
                    cancellationToken);
}

为了达到您的需求,您可以创建自己的自定义扩展方法,明确指定使用XmlSerializer

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