【发布时间】:2012-10-02 11:03:02
【问题描述】:
我在 C#.NET WCF Web 服务上启用 GZIP 压缩时遇到问题,希望有人知道我在 App.conf 配置文件中缺少什么,或者在调用启动代码中的 web 服务。
我点击了链接 Applying GZIP Compression to WCF Services,该链接指向下载 Microsoft 添加 GZIP 的示例,但该示例与我设置 Web 服务的方式无关。
所以我的 App.conf 看起来像
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="MyService.Service1">
<endpoint address="http://localhost:8080/webservice" binding="webHttpBinding" contract="MyServiceContract.IService"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior>
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<bindingElementExtensions>
<add name="gzipMessageEncoding" type="MyServiceHost.GZipMessageEncodingElement, MyServiceHost, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null" />
</bindingElementExtensions>
</extensions>
<protocolMapping>
<add scheme="http" binding="customBinding" />
</protocolMapping>
<bindings>
<customBinding>
<binding>
<gzipMessageEncoding innerMessageEncoding="textMessageEncoding"/>
<httpTransport hostNameComparisonMode="StrongWildcard" manualAddressing="False" maxReceivedMessageSize="65536" authenticationScheme="Anonymous" bypassProxyOnLocal="False" realm="" useDefaultWebProxy="True"/>
</binding>
</customBinding>
</bindings>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
我只是将 MS 示例中的配置和 GZIP 类复制到我的项目中,并添加了我的相关 Web 服务配置。 我用来启动windows服务的代码是:
WebServiceHost webserviceHost = new WebServiceHost(typeof(MyService.Service1));
webserviceHost.Open();
Web 服务运行良好,但 Fiddler 在从 Web 浏览器进行调用时未检测到任何通过 GZIP 压缩返回的响应。我还尝试以编程方式使用 GZIP 设置和运行 Web 服务,但失败了。作为绿色我不确定我还需要配置什么,任何建议都很棒
我对此进行了深入研究,发现由于我将 Web 服务作为 WebServiceHost 对象运行,因此它必须使用 WebServiceHost 默认的 WebHTTPBinding 对象覆盖 app.conf 文件中的自定义 GZIP 绑定,即意味着来自 Web 服务的任何内容都不会被编码。 为了解决这个问题,我想我会以编程方式将自定义 GZIP 绑定写入代码
var serviceType = typeof(Service1);
var serviceUri = new Uri("http://localhost:8080/webservice");
var webserviceHost = new WebServiceHost(serviceType, serviceUri);
CustomBinding binding = new CustomBinding(new GZipMessageEncodingBindingElement(), new HttpTransportBindingElement());
var serviceEndPoint = webserviceHost.AddServiceEndpoint(typeof(IService), binding, "endpoint");
webserviceHost.Description.Endpoints[0].Behaviors.Add(new WebHttpBehavior { HelpEnabled = true });
webserviceHost.Open();
问题在于它不允许与 WebHttpBehavior 进行自定义绑定。但是,如果我删除该行为,那么我的 REST Web 服务就会变得丑陋,并期望 Stream 对象作为我的合同中的输入。我不确定如何配置行为,所以任何帮助都非常有用。
【问题讨论】:
标签: c# .net wcf web-services gzip