Issues with example XML, in Swagger UI
We have a Web API service for which we've only supported JSON, up until now. Now we're tasked with getting it to support XML, and that has exposed some issues that we've been fixing. But there are a couple of issues with Swagger UI that we haven't figured out, yet, particularly in the example values that Swagger UI generates when the user selects Parameter content type: "application/xml". The example XML fails to marshall. Our controller action is pretty simple: [HttpPost, Route("")] public HttpResponseMessage PostNoteForTickets([FromBody] IEnumerable<NoteDto> dto) { ... } And our NoteDto is pretty simple: [DataContract(Namespace = "")] public class NoteDto { [DataMember] public string TicketNumber { get; set; } [DataMember] public string CreatedBy { get; set; } [DataMember] public DateTime? CreatedDateTime { get; set; } [DataMember] public string Contents { get; set; } } The example XML that Swagger generates is simply wrong: <?xml version="1.0"?> <NoteDto> <TicketNumber>string</TicketNumber> <CreatedBy>string</CreatedBy> <CreatedDateTime>1970-01-01T00:00:00.001Z</CreatedDateTime> <Contents>string</Contents> </NoteDto> There are two errors, here. First, dto is an IEnumerable. The JSON sample gets this right, passing an array: [ { "TicketNumber": "string", "CreatedBy": "string", "CreatedDateTime": "2021-01-08T21:08:09.390Z", "Contents": "string" } ] What the XML should be passing is an <ArrayOfNoteDto>: <?xml version="1.0"?> <ArrayOfNoteDto> <NoteDto> <TicketNumber>string</TicketNumber> <CreatedBy>string</CreatedBy> <CreatedDateTime>1970-01-01T00:00:00.001Z</CreatedDateTime> <Contents>string</Contents> </NoteDto> </ArrayOfNoteDto> The second error is the field ordering. DataContract's XMLSerializer imposes an order on the elements. By default, this is alphabetic order. You can override this in the DataMember attribute: [DataMember(Order = 1)] public string TicketNumber { get; set; } But whether you specify an order explicitly, or whether you leave it with the alphabetic default. thereisan imposed order on the elements, and it's not the order in which the fields appear in the class definition. And fields in the submitted XML that appear out of order are simply left null. Now, as I said, this is an older, existing application. It's written in .NET Framework 4.5.1, and we were using Swagger 1.0, and we saw these problems. I upgraded Swagger to 3.0, which seems to be the most recent version that supports .NET Framework 4.5.1, and I'm still seeing these issues. Have they been resolved in more recent versions? Are there known and accepted work-arounds?604Views0likes0Comments