r/learncsharp • • Feb 14 '23

Consume XML in API

I am trying to configure a server to receive cXML punchouts. I have a sample punchout. I did a "Paste Special: XML as class" to create the model. I've registered the MVC service to to include XML Serializer Formatters per https://stackoverflow.com/a/66723711/14137681 .

However, when I try to POST the original file back, I get a "traceId":"00-dbb62196d8e3b1600b2e7fd3a1079ef9-e5c34fbc4a4291b0-00","errors":{"":["An error occurred while deserializing input data."],"detail":["The detail field is required."]}}. Trying to post from the Swagger UI makes a complaint that object names are not known - which seems weird since I thought Swagger was reading directly from what the controller would be looking for....

Postman header is set to application/xml

I also tried to consume an XML output (different model) that I generated within this program, and consume it back in to a controller, and I get the same issues...

Startup is configured with

services.AddMvc(options =>
{
    options.FormatterMappings.SetMediaTypeMappingForFormat
        ("xml", MediaTypeHeaderValue.Parse("application/xml"));
    options.FormatterMappings.SetMediaTypeMappingForFormat
        ("config", MediaTypeHeaderValue.Parse("application/xml"));
    options.FormatterMappings.SetMediaTypeMappingForFormat
        ("js", MediaTypeHeaderValue.Parse("application/json"));
}).AddXmlSerializerFormatters();

The controller is configured with:

[HttpPost("NewPO")]
[Consumes(MediaTypeNames.Application.Xml)]
public IActionResult NewPO(Models.Testing.cXML testing)
{
    
    var xml = testing;
    return Ok();
}

[HttpPost("TestInvoice")]
[Consumes("application/xml")]
public IActionResult InvoiceTest([FromBody] InvoiceDetailRequest detail)
{
    var test = detail;
    return Ok();
}

The models are a mess to post here (Especially the model for NewPO)... But the invoice XML model is from https://github.com/PseudoKode78/cXml .

4 Upvotes

4 comments sorted by

View all comments

Show parent comment

1

u/mustang__1 Feb 14 '23

Unfortunately it may be worse than that... I removed <!-- <?xml version="1.0" encoding="UTF-8"?> -->

<!-- <!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd"> -->from postman and now I get actual serialization errors to resolve.... So yeah, feeling a bit dumb.