简体   繁体   English

如何从Postman将XML传递到ASP.Net核心中的Web API

[英]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. 我有ASP.Net Core 2.1应用程序,我的API控制器如下所示。

 [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. 从邮递员那里,我正在用下面的有效负载调用此API。

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

在此处输入图片说明

But on clicking Send(hit), its throwing 400 Bad Request. 但是,单击“发送”(命中)后,将引发400错误请求。 I tried with adding the below line on the top as well 我尝试在顶部也添加以下行

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

But still the same 400. 但仍然是400。

How do I pass XML to API Controller? 如何将XML传递给API Controller?

Thanks! 谢谢!

ASP.NET Core does not support XML serialization/deserialization by default. 默认情况下,ASP.NET Core不支持XML序列化/反序列化。 You must explicitly enable that: 您必须明确启用:

services.AddMvc()
    .AddXmlSerializerFormatters();

@mason's point in the comments is still relevant, though. 不过,@ mason在评论中的观点仍然有意义。 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. 您永远不应直接绑定到诸如XElementJObject等之类的东西。相反,您将创建一个表示XML文档/ JSON对象的结构的类并进行绑定。 What you actually bind to in your action method has nothing to do with what third-party clients are sending. 您在操作方法中实际绑定的内容与第三方客户端发送的内容无关。

You recieve a request as a strem independently if it was XML, a JSON, or anything. 如果请求是XML,JSON或其他任何内容,则可以独立地将请求作为strem接收。 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. 他们发送的方式无关紧要,但是您如何处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM