HttpClient不能正确序列化XML

Jam*_*ter 9 .net c# 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())
Run Code Online (Sandbox Code Playgroud)

Yuv*_*kov 16

查看源代码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);
}
Run Code Online (Sandbox Code Playgroud)

为了实现您的需求,您可以创建自己的自定义扩展方法,该方法明确指定使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)