5

我有一个简单的回显服务,我在其中定义了一个操作方法和一对请求/响应类型:

[ServiceContract(Name = "EchoService", 
                 Namespace = "http://example.com/services", 
                 SessionMode = SessionMode.NotAllowed)]
public interface IEchoService
{
    [OperationContract(IsOneWay = false,
                       Action = "http://example.com/services/EchoService/Echo", 
                       ReplyAction = "http://example.com/services/EchoService/EchoResponse")]
    EchoResponse Echo(EchoRequest value);
}

数据类型:

[Serializable]
[DataContract(Namespace = "http://example.com/services/EchoService", 
              Name = "EchoRequest")]
public class EchoRequest
{
    public EchoRequest() { }

    public EchoRequest(String value)
    {
        Value = value;
    }

    [DataMember]
    public String Value { get; set; }
}

[Serializable]
[DataContract(Namespace = "http://example.com/services/EchoService", 
              Name = "EchoResponse")]
public class EchoResponse
{
    public EchoResponse() { }

    public EchoResponse(String value)
    {
        Value = value;
    }

    [DataMember]
    public String Value { get; set; }
}

在 EchoRequest 实例上调用 Message.CreateMessage() 会产生:

  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header />
    <s:Body>
      <EchoRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://example.com/services/EchoService">
        <Value>hello, world!</Value>
      </EchoRequest>
    </s:Body>
  </s:Envelope>

...这正是我想要的。但是,服务似乎希望消息正文进一步包装在另一个 XML 元素中,如下所示:

  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header />
    <s:Body>
      <Echo xmlns="http://example.com/services">
        <EchoRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://example.com/services/EchoService">
          <Value>hello, world!</Value>
        </EchoRequest>
      </Echo>
    </s:Body>
  </s:Envelope>

更新: 感谢 Mark 的回复,我在请求/响应类型上探索了 MessageContract 而不是 DataContract。这似乎更接近我想要的,但现在它走得太远了,并且不期望外部类型元素“EchoRequest”。

这令人困惑,因为 Message.CreateMessage 似乎以某种方式始终生成正确的 XML,因此它显然使用了一些默认序列化,我想将服务配置为接受。我只是误解了 Message.CreateMessage 的工作原理吗?

4

2 回答 2

2

IIRC,WCF 默认使用 'Wrapped' 消息样式。如果您希望能够控制消息的序列化方式,您可以通过使用MessageContractAttribute进行装饰来定义显式消息。使用显式消息协定,您可以将IsWrapped属性设置为false

在您的情况下,我认为 EchoRequest 和 EchoResponse 根本不应该是 DataContracts,而是 MessageContracts。在我看来,它们很像 MessageContracts。

于 2009-07-15T10:36:53.887 回答
1

我最终切换到使用 TypedMessageConverter 使用消息合同我是通过这个问题的答案介绍的。那是这里缺少的部分。

于 2012-12-01T02:44:03.960 回答