【问题标题】:Removing duplicate xmlns declarations in WCF output删除 WCF 输出中的重复 xmlns 声明
【发布时间】:2011-07-13 15:15:45
【问题描述】:

我有 WCF 服务,它可以以 List> 的形式接受和返回相当大量的数据。我的问题是典型行的输出如下所示:

   <d:ArrayOfanyType>
    <d:anyType i:type="e:string" xmlns:e="http://www.w3.org/2001/XMLSchema">PJ123</d:anyType>
    <d:anyType i:type="e:double" xmlns:e="http://www.w3.org/2001/XMLSchema">2</d:anyType>
    <d:anyType i:type="e:string" xmlns:e="http://www.w3.org/2001/XMLSchema">216565</d:anyType>
    <d:anyType i:type="e:dateTime" xmlns:e="http://www.w3.org/2001/XMLSchema">1993-09-10T00:00:00</d:anyType>
    <d:anyType i:type="e:string" xmlns:e="http://www.w3.org/2001/XMLSchema">Timesheet W/E 11/9/93 Franklin</d:anyType>
    <d:anyType i:type="e:string" xmlns:e="http://www.w3.org/2001/XMLSchema">CONSULT OF</d:anyType>
    <d:anyType i:type="e:double" xmlns:e="http://www.w3.org/2001/XMLSchema">25</d:anyType>
    <d:anyType i:type="e:double" xmlns:e="http://www.w3.org/2001/XMLSchema">0</d:anyType>
    <d:anyType i:type="e:double" xmlns:e="http://www.w3.org/2001/XMLSchema">25</d:anyType>
  </d:ArrayOfanyType>

因此,每行中的每个值都定义了“e”命名空间,这大大增加了消息的大小。我知道这背后的原因是 DataContractSerializer 不必进行 2 次传递,但以更大的消息大小为代价获得一点处理性能似乎很麻烦。我已经考虑过如何更改数据结构,但字段真的可以是任何东西,我无法避免使用&lt;anyType&gt; 元素。

有人知道拦截 WCF 管道并删除/重组这些命名空间声明的方法吗?

【问题讨论】:

  • 如果消息的大小根本不重要怎么办?如果不影响性能呢?在这种情况下你会关心额外的命名空间声明吗?
  • WCF 会按照您认为合适的方式执行 allow you to format the message,但随后会产生执行此优化的开销。看起来这个优化是一个零和游戏,只是你有更多的代码需要维护。
  • 约翰,我不太确定你会问这个问题,但是......是的,我可能还是有点介意。我已经在使用 HTTP 压缩,所以实际上这可能正在处理它,但这是它的原理! ;)
  • @mackie:真的。如果传输消息不需要时间或资源,您仍然想更改消息格式吗?为什么?
  • 如果您的意思是我希望格式更优雅,但会牺牲性能,那么不会。在这种情况下,我有一种预感,尽管当使用绳索 3G 连接的某人点击保存在大型表单上并且消息是 500k 而不是兆。

标签: wcf namespaces duplicates xml-namespaces


【解决方案1】:

您可以使用自定义编码器来执行此操作 - 此时您可以随意使用 XML。正如 John Saunders 所指出的,这会导致(可能是显着的)性能损失,但它确实有效。下面的代码显示了您将如何处理它。

public class StackOverflow_6681219
{
    [ServiceContract]
    public interface ITest
    {
        [OperationContract]
        List<List<object>> GetData();
    }
    public class Service : ITest
    {
        public List<List<object>> GetData()
        {
            return new List<List<object>>
            {
                new List<object>
                {
                    "PJ123",
                    2.0,
                    "216565",
                    new DateTime(1993, 9, 10),
                    "Timesheet W/E 11/9/93 Franklin",
                    "CONSULT OF",
                    25.0,
                    0.0,
                    25.0
                }
            };
        }
    }
    class MyEncodingBindingElement : MessageEncodingBindingElement
    {
        MessageEncodingBindingElement inner;
        public MyEncodingBindingElement(MessageEncodingBindingElement inner)
        {
            this.inner = inner;
        }

        public override MessageEncoderFactory CreateMessageEncoderFactory()
        {
            return new MyEncoderFactory(this.inner.CreateMessageEncoderFactory());
        }

        public override MessageVersion MessageVersion
        {
            get { return this.inner.MessageVersion; }
            set { this.inner.MessageVersion = value; }
        }

        public override BindingElement Clone()
        {
            return new MyEncodingBindingElement(this.inner);
        }

        public override bool CanBuildChannelListener<TChannel>(BindingContext context)
        {
            return context.CanBuildInnerChannelListener<TChannel>();
        }

        public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context)
        {
            context.BindingParameters.Add(this);
            return context.BuildInnerChannelListener<TChannel>();
        }

        class MyEncoderFactory : MessageEncoderFactory
        {
            MessageEncoderFactory inner;
            public MyEncoderFactory(MessageEncoderFactory inner)
            {
                this.inner = inner;
            }

            public override MessageEncoder Encoder
            {
                get { return new MyEncoder(this.inner.Encoder); }
            }

            public override MessageVersion MessageVersion
            {
                get { return this.inner.MessageVersion; }
            }
        }

        class MyEncoder : MessageEncoder
        {
            MessageEncoder inner;
            public MyEncoder(MessageEncoder inner)
            {
                this.inner = inner;
            }

            public override string ContentType
            {
                get { return this.inner.ContentType; }
            }

            public override string MediaType
            {
                get { return this.inner.MediaType; }
            }

            public override bool IsContentTypeSupported(string contentType)
            {
                return this.inner.IsContentTypeSupported(contentType);
            }

            public override MessageVersion MessageVersion
            {
                get { return this.inner.MessageVersion; }
            }

            public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
            {
                return this.inner.ReadMessage(buffer, bufferManager, contentType);
            }

            public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)
            {
                throw new NotImplementedException();
            }

            public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
            {
                const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/";
                const string SchemaNamespace = "http://www.w3.org/2001/XMLSchema";
                const string ArraysNamespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
                const string SchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";
                ArraySegment<byte> temp = this.inner.WriteMessage(message, maxMessageSize, bufferManager, messageOffset);
                MemoryStream ms = new MemoryStream(temp.Array, temp.Offset, temp.Count);
                XmlDocument doc = new XmlDocument();
                doc.Load(ms);
                bufferManager.ReturnBuffer(temp.Array);
                XmlAttribute rootAttr = doc.CreateAttribute("xmlns", "sch", XmlnsNamespace);
                rootAttr.Value = SchemaNamespace;
                doc.DocumentElement.Attributes.Append(rootAttr);
                XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
                nsManager.AddNamespace("arrays", ArraysNamespace);
                foreach (XmlNode arrayItem in doc.SelectNodes("//arrays:anyType", nsManager))
                {
                    XmlAttribute toRemove = null;
                    XmlAttribute typeAttr = null;
                    foreach (XmlAttribute attr in arrayItem.Attributes)
                    {
                        if (attr.Prefix == "xmlns" && attr.Value == SchemaNamespace)
                        {
                            toRemove = attr;
                        }
                        else if (attr.LocalName == "type" && attr.NamespaceURI == SchemaInstanceNamespace)
                        {
                            typeAttr = attr;
                        }
                    }

                    if (toRemove != null)
                    {
                        arrayItem.Attributes.Remove(toRemove);
                        if (typeAttr != null)
                        {
                            string prefix = toRemove.LocalName;
                            typeAttr.Value = typeAttr.Value.Replace(prefix + ":", "sch:");
                        }
                    }
                }
                ms = new MemoryStream();
                doc.Save(ms);
                byte[] buffer = bufferManager.TakeBuffer((int)ms.Length + messageOffset);
                Array.Copy(ms.GetBuffer(), 0, buffer, messageOffset, (int)ms.Length);
                return new ArraySegment<byte>(buffer, messageOffset, (int)ms.Length);
            }

            public override void WriteMessage(Message message, Stream stream)
            {
                throw new NotImplementedException();
            }
        }
    }
    static Binding ReplaceEncoding(Binding original)
    {
        CustomBinding custom = new CustomBinding(original);
        for (int i = 0; i < custom.Elements.Count; i++)
        {
            MessageEncodingBindingElement mebe = custom.Elements[i] as MessageEncodingBindingElement;
            if (mebe != null)
            {
                custom.Elements[i] = new MyEncodingBindingElement(mebe);
                break;
            }
        }

        return custom;
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        Binding binding = ReplaceEncoding(new BasicHttpBinding());
        host.AddServiceEndpoint(typeof(ITest), binding, "");
        host.Open();
        Console.WriteLine("Host opened");

        ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
        ITest proxy = factory.CreateChannel();
        Console.WriteLine(proxy.GetData());

        ((IClientChannel)proxy).Close();
        factory.Close();

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}

【讨论】:

    猜你喜欢
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    相关资源
    最近更新 更多