We are connecting to an external system that provides a WSDL that expects decimals to be provided to 2 decimal places - i.e.:
<collectionAmount>1000.00</collectionAmount>
However, when our client serializes the SOAP request the decimals appear with a single precision:
<collectionAmount>1000.0</collectionAmount>
We have attempted to use metadata extension:
[MetadataType(typeof(amountSetRequestMetadata))]
public partial class amountSetRequest
{
internal sealed class amountSetRequestMetadata
{
[XmlIgnore]
public decimal collectionAmount { get; set; }
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 14, ElementName = "collectionAmount")]
public string collectionAmountString => "yay!";
}
}
amountSetRequest
is the generated partial class that the WSDL service auto-generator produces. The output XML is no different so this doesn't appear to have any effect on the request.
We would think that this is fairly common, but can't find out much how this is solved. We have seen solutions that extend the base XML serializer.
What is this cleanest way to have a SOAP request serialized in this way?
So we fixed it by slightly hacking the type-system.
It turns out that decimals converted from strings and back to decimals have different precisions. Hence we did:
public void RequestAmount(decimal amount) {
var request = new amountSetRequest()
request.collectionAmount = Convert.ToDecimal(amount.ToString("F2"));
// ...
}
In doing this when the XML serializer sees the decimal, it keeps the precision that the Convert.ToDecimal
uses from ToString
.