When calling HttpClient\'s extension method PostAsXmlAsync
, it ignores the XmlRootAttribute
on the class. Is this behaviour a bug?
Looking at the source code of PostAsXmlAsync, we can see that it uses XmlMediaTypeFormatter
which internally uses DataContractSerializer
and not XmlSerializer
. The former doesn't respect the XmlRootAttribute
:
public static Task PostAsXmlAsync(this HttpClient client, Uri requestUri, T value, CancellationToken cancellationToken)
{
return client.PostAsync(requestUri, value, new XmlMediaTypeFormatter(),
cancellationToken);
}
In order to achieve what you need, you can create a your own custom extension method which explicitly specifies to use XmlSerializer
:
public static class HttpExtensions
{
public static Task PostAsXmlWithSerializerAsync(this HttpClient client, Uri requestUri, T value, CancellationToken cancellationToken)
{
return client.PostAsync(requestUri, value,
new XmlMediaTypeFormatter { UseXmlSerializer = true },
cancellationToken);
}
}