在调用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())
答案 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);
}
}