C# WCF自定义编码器中XMLWriter生成的XML生成命名空间冲突

C# WCF自定义编码器中XMLWriter生成的XML生成命名空间冲突,c#,xml,wcf,soap,xml-namespaces,C#,Xml,Wcf,Soap,Xml Namespaces,我在我的WCF应用程序中使用自定义编码器来写出SOAP消息XML。当我使用WCF中内置的默认XMLtextMessageEncoding时,这很好,但是当我使用自定义编码器时,我发现名称空间有问题-下面的xmlns:a标记(在元素和元素中)为两个不同的名称空间定义了两次,这在解析时会在服务端造成问题 <s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open.org/w

我在我的WCF应用程序中使用自定义编码器来写出SOAP消息XML。当我使用WCF中内置的默认XML
textMessageEncoding
时,这很好,但是当我使用自定义编码器时,我发现名称空间有问题-下面的xmlns:a标记(在元素和元素中)为两个不同的名称空间定义了两次,这在解析时会在服务端造成问题

<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <Action a:mustUnderstand="1" u:Id="_3" xmlns="http://www.w3.org/2005/08/addressing" **xmlns:a="http://schemas.xmlsoap.org/soap/envelope/"**></Action>
    <MessageID u:Id="_4" xmlns="http://www.w3.org/2005/08/addressing">
      <!--Omitted-->
    </MessageID>
    <ActivityId CorrelationId="1" xmlns="http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics">
      <!--Omitted-->
    </ActivityId>
这是我的XmlWriterSettings

XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.Encoding = Encoding.GetEncoding(factory.CharSet);
writerSettings.OmitXmlDeclaration = true;
writerSettings.NamespaceHandling = NamespaceHandling.OmitDuplicates;  

通过使用
XmlDictionaryWriter
而不是
XmlWriter
修复了此问题。幸运的是,我正在使用Utf-8编码,并且可以选择这样做

XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.Encoding = Encoding.GetEncoding(factory.CharSet);
writerSettings.OmitXmlDeclaration = true;
writerSettings.NamespaceHandling = NamespaceHandling.OmitDuplicates;