3

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!

3
  • With Web API, you shouldn't be dealing with XML in your action method. Your parameter should be a strongly typed object (just a plain .NET class) that represents the data you want posted to your API. Then when you post XML or JSON, the framework will use a model binder to convert it to your object's type and pass it as a parameter to your action method. Commented Apr 3, 2019 at 17:45
  • @mason agreed, but I have a scenario where this payload would be coming from a third party system Commented Apr 3, 2019 at 17:47
  • So? It doesn't matter if it came from a 3rd party system or not. That doesn't change anything about what I just said. What is preventing you from creating a class (or set of classes) that represents the data you want to have posted to your Web API? Commented Apr 3, 2019 at 17:50

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.