2

I encountered a problem with the RestSharp library. Defaultly, it serializes DateTime objects using the format dd/MM/yyyy HH:mm:ss. That doesn't work well with my WCF service that only seems to accept yyyy-MM-ddTHH:mm:ss, so I tried to alter the serialization of a request with request.DateFormat = "yyyy-MM-ddTHH:mm:ss.

This property , even though set correctly, seems to be having zero impact on the serialization. At least when using the default RestSharp.Serializers.XmlSerializer. If I tried using the DotNetXmlSerializer, the DateFormat was working, but then the serializer didn't include my XMLNS link and added version & encoding line to the xml output, one or both of which wasn't compatible with the WCF service either.

Does anybody have any suggestions what am I doing wrong with the XmlSerializer ?

Here is the concerned codeblock:

var req = new RestRequest(endpoint, Method.POST);
req.RequestFormat = DataFormat.Xml;
//req.XmlSerializer = new DotNetXmlSerializer();
req.XmlSerializer = new XmlSerializer();
req.DateFormat = DATE_FORMAT;
req.AddBody(model, XMLNS);

Where private const string DATE_FORMAT = "yyyy-MM-ddTHH:mm:ss" and XMLNS is the URL used in the WCF requests (taken from the endpoint /help documentation).

Near
  • 391
  • 4
  • 16

1 Answers1

1

Looks like RestRequest.DateFormat is only used when deserializing:

    /// <summary>
    /// Used by the default deserializers to explicitly set which date format string to use when parsing dates.
    /// </summary>
    public string DateFormat { get; set; }

For serializing you need to set it explicitly on the serializer:

    req.XmlSerializer = new XmlSerializer { DateFormat = DATE_FORMAT };

Note that, for DotNetXmlSerializer, the underlying System.Xml.Serialization.XmlSerializer does not support custom DateTime formats, according to this answer.

Community
  • 1
  • 1
dbc
  • 104,963
  • 20
  • 228
  • 340