您可以将命名空间添加为自定义 Message 实现的一部分,其中包括一个 OnWriteStartEnvelope() 方法,您可以覆盖和添加任何自定义命名空间。然后将消息连接到MessageFormatter,然后使用MessageFormatAttribute 将行为附加到特定方法。
添加命名空间的关键方法在重写的Message 实现上,您可以在其中将命名空间添加到信封:
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");
}
一旦附加到信封,文档的其余部分将重用这些顶级声明的命名空间,而不是内联命名空间。
我写了一篇博文,描述了涉及Message、MessageFormatter 和FormatMessageAttribute 实现的完整过程:
http://weblog.west-wind.com/posts/2016/Apr/02/Custom-Message-Formatting-in-WCF-to-add-all-Namespaces-to-the-SOAP-Envelope