按代码添加ServiceHost扩展

时间:2012-07-28 14:43:13

标签: wcf web-services webhttpbinding

我的这个XML剪辑了App.configfound here

<?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在标记行中进行调试时崩溃。有什么想法吗?

1 个答案:

答案 0 :(得分: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);