我正在尝试解码一个GZiped请求,该请求以内容类型发送到Web服务:application/x-gzip。
我已经实现了一个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) ---内部异常堆栈跟踪结束---
我一整天都在为此烦恼。
附言该请求是使用 GZipMessageEncoder 进行 GZip 编码的,该编码器是从 MSDN 网站上的 WCF 示例项目中取出的。
此错误远远早于您的代码。它在 WCF 框架级别反弹,表示您的服务未配置为接受内容类型"application/x-gzip"。若要解决此问题,请将 WCF 配置为允许所述内容类型。关于如何做到这一点的信息分散在整个网络中,但这是一个良好的开端。您从 MSDN 获得示例代码的位置也可能具有启用 gzip 的示例配置。