HttpClient does not order XML correctly

When calling the HttpClient PostAsXmlAsync extension method, it ignores the XmlRootAttribute in the class. Is this behavior a mistake?

Test

 [Serializable] [XmlRoot("record")] class Account { [XmlElement("account-id")] public int ID { get; set } } var client = new HttpClient(); await client.PostAsXmlAsync(url, new Account()) 
+5
source share
1 answer

Looking at the source code of PostAsXmlAsync , we see that it uses the XmlMediaTypeFormatter , which uses the DataContractSerializer and > not the XmlSerializer . The first does not respect XmlRootAttribute :

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

To achieve what you need, you can create your own custom extension method that explicitly indicates the use of 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); } } 
+10
source

Source: https://habr.com/ru/post/1201095/


All Articles