WCF客户端:强制使用全局命名空间

19
我正在与一个SOAP服务进行接口对接,该服务似乎无法处理默认命名空间,但在SOAP信封级别声明全局命名空间和命名空间前缀时可以正常工作。
问题是WCF不会在根目录创建这些全局命名空间,而是使用显式的未命名默认命名空间,这似乎让服务出现了问题。现在我知道这不是WCF的问题 - 我相信WCF生成的消息是有效的XML,但服务仍然无法处理它。
使用WCF生成的输出如下:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <h:Security xmlns:h="http://docs.oasis-open.org/wss/2004/01/oasis-
          ...
    </h:Security>
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <cancelShipmentRequest xmlns="http://www.royalmailgroup.com/api/ship/V2">
      <integrationHeader>
        <dateTime xmlns="http://www.royalmailgroup.com/integration/core/V1">2016-03-26T01:44:37.0493801Z</dateTime>
        <version xmlns="http://www.royalmailgroup.com/integration/core/V1">2</version>
        <identification xmlns="http://www.royalmailgroup.com/integration/core/V1">
          <applicationId>RMG-API-G-01</applicationId>
          <transactionId>ozhckwej6sxg</transactionId>
        </identification>
      </integrationHeader>
      <cancelShipments>
        <shipmentNumber>TTT001908905GB</shipmentNumber>
      </cancelShipments>
    </cancelShipmentRequest>
  </s:Body>
</s:Envelope>

我可以帮助你进行翻译。以下是需要翻译的内容:

which doesn't work.

使用以下SOAP信封(在SoapUI中手动输入)可以正常工作:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:oas="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
  xmlns:v2="http://www.royalmailgroup.com/api/ship/V2"
  xmlns:v1="http://www.royalmailgroup.com/integration/core/V1">
  <soapenv:Header>
    <h:Security xmlns:h="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
       ...
    </h:Security>
  </soapenv:Header>
  <soapenv:Body>
    <v2:cancelShipmentRequest>
      <v2:integrationHeader>
        <v1:dateTime>2016-03-02T14:55:00Z</v1:dateTime>
        <v1:version>2</v1:version>
        <v1:identification>
          <v1:applicationId>RMG-API-G-01</v1:applicationId>
          <v1:transactionId>wftdaife96gv</v1:transactionId>
        </v1:identification>
      </v2:integrationHeader>
      <v2:cancelShipments>
        <v2:shipmentNumber>TTT001908905GB</v2:shipmentNumber>
      </v2:cancelShipments>
    </v2:cancelShipmentRequest>
  </soapenv:Body>
</soapenv:Envelope>

两者之间的区别在于,v1和v2命名空间在文档顶部全局声明,第二个文档中没有本地命名空间声明。

也许我漏掉了什么,但对我来说,WCF生成的XML看起来是有效的,并且在命名空间方面代表相同的文档状态。

我唯一能发现的区别是命名空间声明的方式。虽然WCF版本似乎是有效的并产生相同的命名空间,但服务会抱怨无效的命名空间引用。

架构验证失败:消息架构验证失败:模式有效性错误:元素 'xmlns':不应出现此元素。期望的是({http://www.royalmailgroup.com/api/ship/V2}integrationHeader)。

问题是,如何最好地强制WCF在顶部添加命名空间引用而不是内联?到目前为止,我找到的唯一方法是使用消息检查器并显式重写消息,但如果我走这条路,我最好手动创建消息。

有什么想法可以尝试强制WCF使用显式命名空间前缀而不是手动重写消息吗?


最近我也遇到了相同的情况,尝试将一个现有的命名空间与一个新的命名空间合并。我无法给出明确的答案。但我发现,在我删除了合并尝试后,重新构建、退出VS,然后集成现有代码后,一切都正常了。我同意这个答案很差。我得出结论,这是VS中的一个bug,但过于复杂,无法尝试重现场景。祝你好运,并期待你的情况有更好的解决方案/答案。 - JamieMeyer
1
你尝试过这篇博客文章中的建议(http://vanacosmin.ro/Articles/Read/WCFEnvelopeNamespacePrefix),或者这个答案(https://dev59.com/HnPYa4cB1Zd3GeqPpfk5#17798306)了吗? - Richard Deeming
谢谢Richard。这篇博客文章很有帮助,指引了我正确的方向。 - Rick Strahl
1个回答

13

解决这个问题的方法是创建一个自定义的 IClientMessageFormatterMessage,然后覆盖 Message.OnWriteStartEnvelope() 方法,以显式地在 Soap 文档根处写出所有命名空间。渲染的文档将重用这些命名空间,而不是显式地在子元素上分配命名空间。

需要创建三个类才能使其工作:

  • 处理实际 OnWriteStartEnvelope() 的 Message 实现
  • 被接入 WCF 的 IClientMessageFormatter
  • 附加到每个客户端方法的 FormatMessageAttribute

下面是这三个类的代码:

public class RoyalMailCustomMessage : Message
{
    private readonly Message message;

    public RoyalMailCustomMessage(Message message)
    {
        this.message = message;
    }
    public override MessageHeaders Headers
    {
        get { return this.message.Headers; }
    }
    public override MessageProperties Properties
    {
        get { return this.message.Properties; }
    }
    public override MessageVersion Version
    {
        get { return this.message.Version; }
    }

    protected override void OnWriteStartBody(XmlDictionaryWriter writer)
    {
        writer.WriteStartElement("Body", "http://schemas.xmlsoap.org/soap/envelope/");
    }
    protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
    {
        this.message.WriteBodyContents(writer);
    }
    protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)
    {
        writer.WriteStartElement("soapenv", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
        writer.WriteAttributeString("xmlns", "oas", null, "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
        writer.WriteAttributeString("xmlns", "v2", null, "http://www.royalmailgroup.com/api/ship/V2");
        writer.WriteAttributeString("xmlns", "v1", null, "http://www.royalmailgroup.com/integration/core/V1");
        writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
        writer.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");            
    }
}

public class RoyalMailMessageFormatter : IClientMessageFormatter
{
    private readonly IClientMessageFormatter formatter;

    public RoyalMailMessageFormatter(IClientMessageFormatter formatter)
    {
        this.formatter = formatter;
    }

    public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
    {
        var message = this.formatter.SerializeRequest(messageVersion, parameters);
        return new RoyalMailCustomMessage(message);
    }

    public object DeserializeReply(Message message, object[] parameters)
    {
        return this.formatter.DeserializeReply(message, parameters);
    }
}


[AttributeUsage(AttributeTargets.Method)]
public class RoyalMailFormatMessageAttribute : Attribute, IOperationBehavior
{
    public void AddBindingParameters(OperationDescription operationDescription,
        BindingParameterCollection bindingParameters)
    { }

    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {
        var serializerBehavior = operationDescription.Behaviors.Find<XmlSerializerOperationBehavior>();

        if (clientOperation.Formatter == null)
            ((IOperationBehavior)serializerBehavior).ApplyClientBehavior(operationDescription, clientOperation);

        IClientMessageFormatter innerClientFormatter = clientOperation.Formatter;
        clientOperation.Formatter = new RoyalMailMessageFormatter(innerClientFormatter);
    }

    public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    { }

    public void Validate(OperationDescription operationDescription) { }
}

大部分是仪式和样板代码。关键代码块是OnWriteStartEnvelope,在其中连接了实际的命名空间,SerializeRequest将格式化程序连接到WCF管道中,以及ApplyClientBehavior将消息格式化程序附加到实际操作上。

要完成这个过程,我在服务接口的客户端方法上添加了属性 - 在这种情况下是在我的生成的WCF客户端中的Reference.cs文件中。

    // CODEGEN: Generating message contract since the operation cancelShipment is neither RPC nor document wrapped.
    [System.ServiceModel.OperationContractAttribute(Action="cancelShipment", ReplyAction="*")]
    [System.ServiceModel.FaultContractAttribute(typeof(MarvelPress.Workflow.Business.RoyalShippingApi.exceptionDetails), Action="cancelShipment", Name="exceptionDetails")]
    [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
    [System.ServiceModel.ServiceKnownTypeAttribute(typeof(contactMechanism))]
    [System.ServiceModel.ServiceKnownTypeAttribute(typeof(baseRequest))]
    [RoyalMailFormatMessage()]
    MarvelPress.Workflow.Business.RoyalShippingApi.cancelShipmentResponse1 cancelShipment(MarvelPress.Workflow.Business.RoyalShippingApi.cancelShipmentRequest1 request);

现在从WCF生成的消息看起来符合预期,因为所有命名空间都在文档顶部定义:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:oas="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:v2="http://www.royalmailgroup.com/api/ship/V2" xmlns:v1="http://www.royalmailgroup.com/integration/core/V1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <s:Header xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <h:Security>...</h:Security>
  </s:Header>
  <soapenv:Body>
    <v2:cancelShipmentRequest>
      <v2:integrationHeader>
        <v1:dateTime>2016-04-02T01:04:50.4122473Z</v1:dateTime>
        <v1:version>2</v1:version>
        <v1:identification>
          <v1:applicationId>RMG-API-G-01</v1:applicationId>
          <v1:transactionId>fshrxevdnc7n</v1:transactionId>
        </v1:identification>
      </v2:integrationHeader>
      <v2:cancelShipments>
        <v2:shipmentNumber>TTT001908905GB</v2:shipmentNumber>
      </v2:cancelShipments>
    </v2:cancelShipmentRequest>
  </soapenv:Body>
</soapenv:Envelope>    

想了解更多信息以及通用名称空间添加格式化程序,请查看我的相关博客文章:http://weblog.west-wind.com/posts/2016/Apr/02/Custom-Message-Formatting-in-WCF-to-add-all-Namespaces-to-the-SOAP-Envelope


4
未经授权部分剽窃自 https://dev59.com/xY3da4cB1Zd3GeqPyVbz#31597758不好。 - Ashley Swatton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接