在 .NET Core Web API 中接收 XML 格式的字符串
[!info]
以下内容基于 ASP.NET Core 3.1,更多版本详细内容请查看官方文档 ASP.NET Core 中的模型绑定 | Microsoft Learn
配置 Web API 以接受 XML
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddXmlSerializerFormatters();
}
在模型类中打上 XML 特性
[XmlRoot("root")]
public class TestXml
{
[XmlElement("UserId")]
public string UserId { get; set; }
[XmlElement("UserName")]
public string UserName { get; set; }
[XmlElement("Item")]
public List<TestXmlItem> Item { get; set; }
}
public class TestXmlItem
{
[XmlElement("Phone")]
public string Phone { get; set; }
}
测试 XML
Web API 接口:
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
[HttpPost("xmlTest")]
public IActionResult XmlTest([FromBody] TestXml xml)
{
return Ok(xml);
}
}
请求:
<root>
<UserId>12345</UserId>
<UserName>Test</UserName>
<Item>
<Phone>18285682650</Phone>
</Item>
<Item>
<Phone>17678382089</Phone>
</Item>
</root>
响应:
{
"userId": "12345",
"userName": "Test",
"item": [
{
"phone": "18285682650"
},
{
"phone": "17678382089"
}
]
}