使用 WCF 时如何为 OperationContract 指定命名空间?

How can I specify a namespace for OperationContract when using WCF?

我正在为服务器创建客户端api我无法更改。我的客户目前生成这种格式:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <StoreSomething xmlns="urn:aaa">
      <Something>
        <SomeText xmlns="urn:bbb">My text</SomeText>
      </Something>
    </StoreSomething>
  </s:Body>
</s:Envelope>

但是,服务器希望 Somethingurn:bbb 命名空间中(即移动 xmlns属性上一级)。我怎样才能做到这一点? OperationContractAttribute 没有命名空间 属性.

代码:

using System;
using System.ServiceModel;
using System.Xml.Serialization;

[XmlType(Namespace="urn:bbb")]
public class Something
{
    public string SomeText { get; set; }
}

[XmlSerializerFormat]
[ServiceContract(Namespace="urn:aaa")]
public interface IMyService
{
    [OperationContract]
    void StoreSomething(Something Something);
}

class Program
{
    static void Main(string[] args)
    {
        var uri = new Uri("http://localhost/WebService/services/Store");
        var factory = new ChannelFactory<IMyService>(new BasicHttpBinding(), new EndpointAddress(uri));
        IMyService service = factory.CreateChannel();

        service.StoreSomething(new Something
        {
            SomeText = "My text"
        });
    }
}

我设法通过使用 unwrapped messages 让它工作。不幸的是,这导致方法名称 参数名称都被遗漏了。因此,我不得不创建包装器 类,这会导致代码复杂。

无论如何,这里是让它工作的代码:

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    [XmlSerializerFormat]
    void StoreSomething(StoreSomethingMessage message);
}

[MessageContract(IsWrapped=false)]
public class StoreSomethingMessage
{
    [MessageBodyMember(Namespace="urn:aaa")]
    public StoreSomething StoreSomething { get; set; }
}

[XmlType(Namespace="urn:bbb")]
public class StoreSomething
{
    public Something Something { get; set; }
}

public class Something
{
    public string SomeText { get; set; }
}

我还创建了一个 MyServiceClient,它实现了 IMyService 并继承自 ClientBase,因为 IMyService 现在需要一个 StoreSomethingMessage 对象,但为了简单起见,我省略了那部分。

我希望有一个更简单的解决方案。