我在这里找到了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());
但最后一行不起作用,我该怎么解决?我认为通过代码一定可以做到这一点。
现在我几乎找到了一个解决方案,当我尝试使用JsonSerializer时,我遇到了一个问题,但我现在使用这个绑定:
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;
}
}
但是我的代码让visualstudio在标记行中调试时崩溃。有什么想法吗?
它不能以这种方式工作。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);