I have this XML snipped of a App.config
which I found 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>
...
For some reasons I don't want to hardcode the asembly and I don't want to use a XML file for that.
Curriently I use this code:
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());
But the last line does not work how can I fix that? I think it must be possible to do that by code.
Curriently I found almost an solution I have just a problem when I try to use the JsonSerialisator however I use this binding now:
CustomBinding cb = new CustomBinding(binding);
MessageEncodingBindingElement inner = (MessageEncodingBindingElement)cb.Elements.ToArray()[0];
cb.Elements.RemoveAt(0);
cb.Elements.Insert(0, new GZipMessageEncodingBindingElement(inner));
The GZipMessageEncoder
is a little modified to make the compression optinal:
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;
}
}
But my code let visual studio crash while debugging in the marked line. Any ideas?