0

我有一个App.config在这里找到的 XML 剪辑:

<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <extensions>
      <bindingElementExtensions>
        <add name="gzipMessageEncoding" type="Microsoft.Samples.GZipEncoder.GZipMessageEncodingElement, GZipEncoder, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null" />
      </bindingElementExtensions>
    </extensions>
...

由于某些原因,我不想对程序集进行硬编码,也不想为此使用 XML 文件。

目前我使用这段代码:

Uri baseAddress = new Uri("http://localhost:80/Test");
WebHttpBinding binding = new WebHttpBinding(
                                    WebHttpSecurityMode.TransportCredentialOnly);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
ServiceHost host = new ServiceHost(typeof(ExampleWebService), baseAddress);
host.Extensions.Add(new GZipMessageEncodingElement());

但是最后一行不起作用,我该如何解决?我认为必须可以通过代码来做到这一点。


目前,我几乎找到了一个解决方案,当我尝试使用 JsonSerialisator 时,我遇到了一个问题,但是我现在使用这个绑定:

CustomBinding cb = new CustomBinding(binding);
MessageEncodingBindingElement inner = (MessageEncodingBindingElement)cb.Elements.ToArray()[0];
cb.Elements.RemoveAt(0);
cb.Elements.Insert(0, new GZipMessageEncodingBindingElement(inner));

GZipMessageEncoder稍作修改以使压缩成为可选:

public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset) {
    var req = WebOperationContext.Current.IncomingRequest;
    var encoding=req.Headers[HttpRequestHeader.AcceptEncoding]; // crash while debug
    //Use the inner encoder to encode a Message into a buffered byte array
    ArraySegment<byte> buffer = innerEncoder.WriteMessage(message, maxMessageSize, bufferManager, 0);
    if(encoding != null && encoding.ToLower().Contains("gzip")) {
        WebOperationContext.Current.OutgoingResponse.Headers[HttpResponseHeader.ContentEncoding] = "gzip";
        WebOperationContext.Current.OutgoingRequest.Headers[HttpResponseHeader.ContentEncoding] = "gzip";
        //Compress the resulting byte array
        return CompressBuffer(buffer, bufferManager, messageOffset);
    } else {
        return buffer;
    }
}

但是我的代码在标记行中调试时让 Visual Studio 崩溃。有任何想法吗?

4

1 回答 1

2

这种方式行不通。WebHttpBinding永远不会使用您的绑定元素。BindingElementExtensions在配置文件中只定义了可用于在配置文件中定义的新元素CutomBinding。如果您需要在代码中执行此操作,您只需创建一个新实例CustomBinding并用您要使用的绑定元素(派生自 的类BindingElement)填充它 - 您将使用GZipMessageEncodingBindingElement. 链接的示例也描述了该代码:

ICollection<BindingElement> bindingElements = new List<BindingElement>();
HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
GZipMessageEncodingBindingElement compBindingElement = new GZipMessageEncodingBindingElement ();
bindingElements.Add(compBindingElement);
bindingElements.Add(httpBindingElement);
CustomBinding binding = new CustomBinding(bindingElements);
于 2012-07-30T08:51:17.680 回答