Search code examples
c#xmlpostmanasp.net-core-webapiasp.net-core-2.1

how to pass XML to Web API in ASP.Net core from Postman


I have ASP.Net Core 2.1 application & my API controllers look as below.

 [HttpPost]
    public async Task<IActionResult> Post([FromBody]XElement recurlyXml)
    {
        var node = _xmlUtil.GetFirstNode(recurlyXml);
        //do something
        return Ok();
    }

From postman, I am calling this API with below payload.

<updated_subscription_notification>
 <subscription>
    <plan>
        <plan_code>1dpt</plan_code>
        <name>Subscription One</name>
    </plan>
    <uuid>292332928954ca62fa48048be5ac98ec</uuid>
</subscription>
</updated_subscription_notification>

enter image description here

But on clicking Send(hit), its throwing 400 Bad Request. I tried with adding the below line on the top as well

<?xml version="1.0" encoding="UTF-8"?>

But still the same 400.

How do I pass XML to API Controller?

Thanks!


Solution

  • ASP.NET Core does not support XML serialization/deserialization by default. You must explicitly enable that:

    services.AddMvc()
        .AddXmlSerializerFormatters();
    

    @mason's point in the comments is still relevant, though. The type of the request body is and should be virtually inconsequential. You should never bind directly to something like XElement, JObject, etc. Rather, you create a class that represents the structure of your XML document/JSON object and bind to that. What you actually bind to in your action method has nothing to do with what third-party clients are sending.