如何让ASP.NET Core 8 Web API正确解析带soapenv前缀的SOAP XML?
问题描述
我正在编写一个可接收SOAP XML并返回XML响应的ASP.NET Core 8 Web API,已实现以下内容:
控制器代码
[HttpPost] [Produces("application/xml")] [Consumes("application/xml")] public IActionResult Get(TestThing inputXml) { return Ok(); }
XML格式化器配置
builder.Services.AddControllers() .AddXmlSerializerFormatters();
请求类定义
[XmlRoot("TestThing", Namespace = "http://www.w3.org/2003/05/soap-envelope/")] public partial class TestThing { public string? Header { get; set; } }
当发送不带前缀的XML请求时可正常工作:
<TestThing xmlns="http://www.w3.org/2003/05/soap-envelope/"> <Header>sdfs sdfsd sdfsdfs sdfsdf</Header> </TestThing>
但发送带soapenv前缀的目标XML时,会报错An error occurred while deserializing input data:
<soapenv:ETestThing xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope/"> <soapenv:Header>sdfs sdfsd sdfsdfs sdfsdf</soapenv:Header> </soapenv:ETestThing>
需要解决如何正确反序列化带命名空间前缀的SOAP XML的问题。
解决方案
导致反序列化失败的核心原因有两个:根元素名称不匹配、属性未显式指定命名空间,按以下步骤修改即可:
修正根元素名称
目标XML的根元素是ETestThing,而非当前类定义的TestThing,需要更新XmlRoot特性的元素名称:[XmlRoot("ETestThing", Namespace = "http://www.w3.org/2003/05/soap-envelope/")] public partial class TestThing { // ... }为属性指定命名空间
XML中的Header元素带有soapenv前缀,意味着它属于http://www.w3.org/2003/05/soap-envelope/命名空间,需要为属性添加XmlElement特性并指定命名空间:[XmlRoot("ETestThing", Namespace = "http://www.w3.org/2003/05/soap-envelope/")] public partial class TestThing { [XmlElement(Namespace = "http://www.w3.org/2003/05/soap-envelope/")] public string? Header { get; set; } }验证命名空间一致性
确保所有XML元素的命名空间与类特性中指定的完全一致,前缀(如soapenv)只是命名空间的别名,XML序列化器只会识别命名空间字符串,不会在意前缀名称。
修改完成后,重新测试带soapenv前缀的XML请求即可正常反序列化。
内容的提问来源于stack exchange,提问作者Art
相关产品推荐
相关产品推荐

