Kgn-web
Kgn-web

Reputation: 7555

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!

Upvotes: 3

Views: 6513

Answers (2)

Ramiro G.M.
Ramiro G.M.

Reputation: 477

You recieve a request as a strem independently if it was XML, a JSON, or anything. The data received is decoded by you on the other side of this bridge and transformed to whatever object you desire. How they send it doesn't care, but what you do with it.

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239250

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.

Upvotes: 2

Related Questions