Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

c# - HttpClient does not serialize XML correctly

When calling HttpClient's extension method PostAsXmlAsync, it ignores the XmlRootAttribute on the class. Is this behaviour a bug?

Test

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


var client = new HttpClient();
await client.PostAsXmlAsync(url, new Account())
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<HttpResponseMessage> PostAsXmlAsync<T>(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<HttpResponseMessage> PostAsXmlWithSerializerAsync<T>(this HttpClient client, Uri requestUri, T value, CancellationToken cancellationToken)
    {
        return client.PostAsync(requestUri, value,
                      new XmlMediaTypeFormatter { UseXmlSerializer = true },
                      cancellationToken);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...