webservice无法获取gzip压缩请求数据

时间:2013-12-17 19:28:49

标签: c# wcf web-services gzip content-type

我正在尝试使用Content-Type:application / x-gzip解码发送到Web服务的GZipped请求。

我已经实现了一个HttpHandler,它添加了一个GZip解压缩过滤器,它似乎正在工作。这是代码:

    void context_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;
        HttpContext ctx = app.Context;

        if (!ctx.Request.Url.PathAndQuery.ToLower().Contains(".asmx"))
            return;

        // test
        if ("gzip" == ctx.Request.Headers["Content-encoding"])
        {
            app.Request.Filter = new GZipStream(app.Request.Filter,
               CompressionMode.Decompress);
        }

        if (IsEncodingAccepted("gzip"))
        {

            app.Response.Filter = new GZipStream(app.Response.Filter,
      CompressionMode.Compress);
            SetEncoding("gzip");
        }
        else if (IsEncodingAccepted("deflate"))
        {
            app.Response.Filter = new DeflateStream(app.Response.Filter,
      CompressionMode.Compress);
            SetEncoding("deflate");
        }
    }
    private bool IsEncodingAccepted(string encoding)
    {
        return HttpContext.Current.Request.Headers["Accept-encoding"] != null &&
          HttpContext.Current.Request.Headers["Accept-encoding"].Contains(encoding);
    }
    private void SetEncoding(string encoding)
    {
        HttpContext.Current.Response.AppendHeader("Content-encoding", encoding);
    }

不幸的是,我一直都会遇到这个错误:

System.ServiceModel.ProtocolException: Content Type application/x-gzip was not supported by service https://127.0.0.1/ModuloWS.asmx.  The client and service bindings may be mismatched. ---> System.Net.WebException: The remote server returned an error: (415) Unsupported Media Type.

at System.Net.HttpWebRequest.GetResponse()    at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)    ---内部异常堆栈跟踪结束---

我整整一天都在为此疯狂。

P.S。该请求是使用GZipMessageEncoder进行GZip编码的,该编码是从MSDN网站上的WCF示例项目中取出的。

1 个答案:

答案 0 :(得分:1)

此错误远远超出您的代码。它在WCF框架级别上反弹,表示您的服务未配置为接受内容类型“application / x-gzip”。要解决此问题,请配置WCF以允许所述内容类型。关于如何这样做的信息分散在整个网络中,但是this is a good start。从MSDN获得示例代码的地方也可能有启用gzip的示例配置。