You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core中SOAP请求体绑定C#类问题求助

修复SOAP请求数据绑定的C#类问题

原代码存在命名空间配置错误、元素类型定义不当等问题,以下是修正后的完整C#类:

using System.Xml.Serialization;

// Brand子元素,无需XmlRoot(仅根节点需要)
public class Brand
{
    [XmlAttribute(AttributeName = "type", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string Type { get; set; }

    [XmlText]
    public string Text { get; set; }
}

// DatiPratica对应的类型定义
[XmlType(TypeName = "ElementiDatiPratica", Namespace = "http://crogwebnew.satoprg.net/soap")]
public class DatiPratica
{
    [XmlElement(ElementName = "Brand")]
    public Brand Brand { get; set; }

    [XmlAttribute(AttributeName = "type", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string Type { get; set; }
}

// RichiestaFin元素
public class RichiestaFin
{
    [XmlElement(ElementName = "DatiPratica")]
    public DatiPratica DatiPratica { get; set; }

    [XmlAttribute(AttributeName = "encodingStyle", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public string EncodingStyle { get; set; }
}

// SOAP Body元素
[XmlType(Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Body
{
    [XmlElement(ElementName = "RichiestaFin")]
    public RichiestaFin RichiestaFin { get; set; }
}

// SOAP Envelope根元素
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
    [XmlElement(ElementName = "Header", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public object Header { get; set; } // 空Header用object类型,避免序列化错误

    [XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public Body Body { get; set; }

    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces = new XmlSerializerNamespaces();

    public Envelope()
    {
        Namespaces.Add("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
        Namespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        Namespaces.Add("xsd", "http://www.w3.org/2001/XMLSchema");
        Namespaces.Add("soap", "http://crogwebnew.satoprg.net/soap");
    }
}

关键修正点说明:

  • 命名空间统一管理:移除冗余的命名空间属性声明,通过XmlSerializerNamespaces统一添加所有需要的前缀,避免冲突。
  • 元素类型修正:将Header类型从string改为object,空Header序列化时会生成正确的空元素,而非文本节点。
  • XmlRoot与XmlType区分:仅根元素Envelope使用XmlRoot,子元素使用XmlType或默认配置,避免命名空间混乱。
  • DatiPratica类型属性:确保xsi:type指向正确的服务命名空间,并添加对应的前缀声明。
  • RichiestaFin命名空间:修正原代码错误指定的xsd命名空间,匹配SOAP结构的默认无命名空间配置。

内容的提问来源于stack exchange,提问作者smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 19:47:35