[英]How to submit valid XML in a POST request body to an ASP.NET Core Web API that consumes XML?
I've installed the Microsoft.AspNetCore.Mvc.Formatters.Xml
and set it up as follows in ConfigureServices()
:我已经安装了Microsoft.AspNetCore.Mvc.Formatters.Xml
并在ConfigureServices()
了如下ConfigureServices()
:
services.AddMvc().AddXmlSerializerFormatters();
Now, I've created a simple Web API as follows:现在,我创建了一个简单的 Web API,如下所示:
[HttpPost]
[Consumes("application/json", new string[]{"application/xml"})]
public ActionResult<string> OnPost([FromBody] ZapScan scan)
{
return scan.ToString();
}
that accepts a ZapScan
through model binding:通过模型绑定接受ZapScan
:
public class ZapScan
{
public string Url { get; set; }
public bool Priority { get; set; }
public override string ToString()
{
return $"url={Url}, priority={Priority}\n";
}
}
However, whatever XML I send from Postman is rejected, eg:但是,我从 Postman 发送的任何 XML 都被拒绝,例如:
<?xml version="1.0" encoding="UTF-8"?>
<zapscan>
<url>http://www.example.cm</url>
<priority>false</priority>
</zapscan>
results in:结果是:
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|f16a42f4-4c8f4678c6f84eb7.","errors":{"":["An error occurred while deserializing input data."]}}
How to properly format XML in a POST request body to a ASP.NET Web API that consumes XML?如何将 POST 请求正文中的 XML 正确格式化为使用 XML 的 ASP.NET Web API?
Your XML is invalid.您的 XML 无效。 You have two opening <zapscan>
tags and no closing tag.你有两个开始<zapscan>
标签,没有结束标签。
<?xml version="1.0" encoding="UTF-8"?>
<zapscan>
<url>http://www.example.cm</url>
<priority>false</priority>
<zapscan> <-- this needs to be a closing tag
Additionally you have an issue with casing, as already covered in the comments.此外,您在大小写方面存在问题,如评论中所述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.