HttpClient does not serialize XML correctly

前端 未结 1 922
你的背包
你的背包 2020-12-15 09:21

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

1条回答
  •  有刺的猬
    2020-12-15 09:49

    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);
        }
    }
    

    0 讨论(0)
提交回复
热议问题