我有一个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 崩溃。有任何想法吗?